pipeline {
    agent any

    tools {
        jdk 'jdk21'
    }

    parameters {
        string(
            name: 'DEPLOY_SERVERS'
        )
        choice(
            name: 'spring.profiles.active',
            choices: ['dev', 'test', 'prod'],
            description: '选择要激活的 Spring Profile'
        )
        choice(
            name: 'BRANCH_NAME',
            choices: ['master', 'dev'],
            description: '要构建的 Git 分支名称'
        )
    }

    environment {
        BASE_IMAGE_NAME = 'seer-gateway'
        SSH_CREDENTIALS_ID = 'seerTeachPubKey'
        DEPLOY_USER = 'root'
        LOGS_HOST_PATH = '/app/java/seer-gateway/logs'
        LOGS_CONTAINER_PATH = '/app/java/seer-gateway/logs'
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
        skipDefaultCheckout(true)
    }

    stages {
        stage('初始化 & 分支校验') {
            steps {
                script {
                    sh 'echo "初始Git工作目录: $(pwd)"'
                    sh 'ls -la '
                    checkout scm

                    def branch = params.BRANCH_NAME
                    env.BRANCH = branch
                    env.IMAGE_TAG = "${BASE_IMAGE_NAME}:${branch}"
                    env.TAR_FILE = "${BASE_IMAGE_NAME}_${branch}.tar"

                    echo " 初始化完成"
                    echo "分支：${env.BRANCH}"
                    echo "镜像标签：${env.IMAGE_TAG}"
                }
            }
        }

        stage('构建 Maven 项目') {
            steps {
                sh 'echo "初始工作目录: $(pwd)"'
                sh 'ls -la '
                sh 'mvn clean package -Dmaven.test.skip=true  -pl seer-gateway -am '
                echo " Maven 构建完成"
            }
        }

        stage('构建 Docker 镜像') {
            steps {
                dir('seer-gateway') {
                    sh "docker build -t ${env.IMAGE_TAG} ."
                    echo " Docker 镜像构建成功：${env.IMAGE_TAG}"
                }

            }
        }

        stage('导出并传输镜像') {
            steps {
                script {
                    sh 'echo "导出并传输镜像工作目录: $(pwd)"'
                    sh "docker save -o ${env.TAR_FILE} ${env.IMAGE_TAG}"
                    echo "镜像已导出为文件：${env.TAR_FILE}"

                    def servers = params.DEPLOY_SERVERS.split(',')
                    servers.each { server ->
                         sshagent([env.SSH_CREDENTIALS_ID]) {
                              def sev = server.trim()
                              sh "scp -o StrictHostKeyChecking=no ${env.TAR_FILE} ${DEPLOY_USER}@${sev}:/tmp/"
                         }
                         echo " 镜像已传输到远程服务器：${server}"
                    }

                }
            }
        }

        stage('远程部署镜像') {
            steps {
                script {
                    def servers = params.DEPLOY_SERVERS.split(',')
                    servers.each { server ->
                       deployToServer(server.trim())
                    }
                }


            }
        }
    }

    post {
        always {
            script {
                if (env.TAR_FILE?.trim()) {
                    sh "rm -f ${env.TAR_FILE} || true"
                }
                deleteDir()
            }
        }
        success {
            echo " 构建成功：分支 ${env.BRANCH}，镜像 ${env.IMAGE_TAG}"
        }
        failure {
            echo " 构建失败：分支 ${env.BRANCH}"
        }
    }
}

def deployToServer(server){
    sshagent([env.SSH_CREDENTIALS_ID]) {
        sh """
        ssh -o StrictHostKeyChecking=no ${DEPLOY_USER}@${server} << 'EOF'
        set -e
        echo "🛠 加载镜像..."
        docker load -i /tmp/${env.TAR_FILE}

        echo " 停止并移除旧容器（如果存在）..."
        docker stop ${BASE_IMAGE_NAME} || true
        docker rm ${BASE_IMAGE_NAME} || true

        echo " 创建日志目录..."
        mkdir -p ${LOGS_HOST_PATH}

        echo " 启动新容器..."
        docker run -d --name ${BASE_IMAGE_NAME} -p 8085:8085 \\
                -v ${LOGS_HOST_PATH}:${LOGS_CONTAINER_PATH} \\
                -e spring.cloud.nacos.discovery.ip=${server} \\
                -e spring.profiles.active=${params['spring.profiles.active']} \\
                --restart=always \\
                ${env.IMAGE_TAG}
EOF
        """
        echo " 镜像已部署到远程服务器：${server}"
    }
}
