pipeline {
  agent any
  options { timestamps(); disableConcurrentBuilds() }

  environment {
    // ====== 宿主机 SSH（关键：Jenkins 在容器里，所有 build/deploy 都到宿主机上跑）======
    HOST_SSH_CRED = "gitea-ssh"
    HOST_SSH_USER = "root"
    HOST_SSH_PORT = "22"
    // 推荐先用 172.17.0.1（容器到宿主机），不通再换公网IP
    HOST_SSH_HOST = "172.17.0.1"

    // ====== 你的项目 ======
    REPO_SSH  = "ssh://git@122.51.109.52:222/root/agri.git"   // gitea 仓库
    BRANCH    = "master"
    BOOT_MODULE = "agri-admin"   // 多模块启动模块（按你实际改）

    // ====== 宿主机构建与部署路径 ======
    BUILD_DIR = "/opt/agri/build/agri-prod"
    DEPLOY_DIR = "/opt/agri"
    DEPLOY_JAR = "/opt/agri/agri.jar"
  }

  stages {
    stage("Checkout (Jenkins only for commit id)") {
      steps {
        checkout scm
        sh 'git rev-parse --short HEAD'
      }
    }

    stage("Build & Deploy on Host (no docker)") {
      steps {
        sshagent(credentials: [env.HOST_SSH_CRED]) {
          sh '''
            set -eux
            # 让宿主机拉代码并按本次构建的 commit 精准构建
            ssh -p ${HOST_SSH_PORT} -o StrictHostKeyChecking=no ${HOST_SSH_USER}@${HOST_SSH_HOST} "
              set -eux

              # 1) 准备构建目录
              sudo mkdir -p ${BUILD_DIR}
              sudo chown -R $(whoami):$(whoami) ${BUILD_DIR}

              if [ ! -d ${BUILD_DIR}/.git ]; then
                rm -rf ${BUILD_DIR}/*
                git clone -b ${BRANCH} ${REPO_SSH} ${BUILD_DIR}
              fi

              cd ${BUILD_DIR}
              git fetch --all --prune
              git checkout -f ${GIT_COMMIT}

              # 2) 宿主机本地打包（用你宿主机装的 JDK8 + Maven）
              java -version
              mvn -v
              mvn -B -DskipTests -pl ${BOOT_MODULE} -am clean package

              # 3) 找 jar，并部署到 /opt/agri/agri.jar
              jar=\$(ls -1 ${BOOT_MODULE}/target/*.jar | grep -v 'sources\\|javadoc\\|original' | head -n 1)
              echo \"picked jar: \$jar\"

              sudo mkdir -p ${DEPLOY_DIR}
              sudo cp -f ${DEPLOY_JAR} ${DEPLOY_DIR}/agri.jar.bak 2>/dev/null || true
              sudo cp -f \"\$jar\" ${DEPLOY_DIR}/agri.jar.new
              sudo mv -f ${DEPLOY_DIR}/agri.jar.new ${DEPLOY_JAR}

              # 4) 重启服务
              sudo systemctl restart agri
              sudo systemctl status agri --no-pager | tail -n 30
            "
          '''
        }
      }
    }
  }
}
