pipeline {
    agent none

    environment {
        // 仓库
        REPO_URL = 'http://47.108.184.184/gitea/HuXiaoHei/Game.git'
        REPO_CREDENTIALS_ID = '80805ba2-f4ac-4d84-aee6-d4cce5fc0a96'

        // Registry
        REGISTRY_URL = 'registry.hlsq.asia'
        REGISTRY_CREDENTIALS_ID = '0d79fc0b-a150-470b-bd0d-2639b2826031'

        // 部署目标服务器
        SERVER_HOST = 'www.hlsq.asia'
        SERVER_USER = 'root'
        SSH_CREDENTIALS_ID = '10e0830d-4d03-4879-9ee4-03a4c55513ad'

        // 基础信息
        APP_NAME = 'server-gateway'
        GO_MOD_CACHE_DIR = '/home/pi/Desktop/docker/jenkins/caches/go-mod'
        GO_BUILD_CACHE_DIR = '/home/pi/Desktop/docker/jenkins/caches/go-build'
    }

    options {
        skipDefaultCheckout true
    }

    stages {
        stage('Checkout') {
            agent any
            steps {
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: '*/master']],
                    doGenerateSubmoduleConfigurations: false,
                    extensions: [],
                    userRemoteConfigs: [[
                        credentialsId: env.REPO_CREDENTIALS_ID,
                        url: env.REPO_URL
                    ]]
                ])
                // 立刻保存Git的Commit，避免并发问题
                script {
                    def shortCommit = sh(script: 'git rev-parse --short=8 HEAD', returnStdout: true).trim()
                    env.IMAGE_TAG = "${env.REGISTRY_URL}/${env.APP_NAME}:${shortCommit}"
                    echo "Checked out commit: ${env.IMAGE_TAG}"
                }
            }
        }

        stage('Build Go Binary') {
            agent {
                docker {
                    image 'golang:1.23.1-alpine'
                    reuseNode true
                    args '-u root:root -v $GO_MOD_CACHE_DIR:/go/pkg/mod -v $GO_BUILD_CACHE_DIR:/root/.cache/go-build'
                }
            }
            steps {
                dir('Server/gateway') {
                    sh """
                        export GOPROXY=https://goproxy.cn,direct
                        export CGO_ENABLED=0
                        export GOOS=linux
                        export GOARCH=amd64

                        go build -o ${env.APP_NAME} .
                    """
                }
            }
        }

        stage('Push Docker Image') {
            agent any
            steps {
                dir('Server/gateway') {
                    script {
                        withCredentials([usernamePassword(
                            credentialsId: env.REGISTRY_CREDENTIALS_ID,
                            usernameVariable: 'DOCKER_USER',
                            passwordVariable: 'DOCKER_PASS'
                        )]) {
                            sh """
                                echo "$DOCKER_PASS" | docker login --username "$DOCKER_USER" --password-stdin ${env.REGISTRY_URL}
                                docker build -t ${env.IMAGE_TAG} .
                                docker push ${env.IMAGE_TAG}
                                docker rmi ${env.IMAGE_TAG}
                                docker logout ${env.REGISTRY_URL}
                            """
                        }
                    }
                }
            }
        }

        stage('Deploy to Server') {
            agent any
            steps {
                script {
                    withCredentials([
                        usernamePassword(
                            credentialsId: env.REGISTRY_CREDENTIALS_ID,
                            usernameVariable: 'DOCKER_USER',
                            passwordVariable: 'DOCKER_PASS'
                        )
                    ]) {
                        sshagent (credentials: [env.SSH_CREDENTIALS_ID]) {
                            sh """
                                ssh -o StrictHostKeyChecking=no ${env.SERVER_USER}@${env.SERVER_HOST} << EOF
                                set -e
                                echo '${DOCKER_PASS}' | docker login --username '${DOCKER_USER}' --password-stdin ${env.REGISTRY_URL}
                                docker pull ${env.IMAGE_TAG}
                                docker stop ${env.APP_NAME} 2>/dev/null || true
                                docker rm ${env.APP_NAME} 2>/dev/null || true
                                docker run -d \\
                                    --name ${env.APP_NAME} \\
                                    --restart unless-stopped \\
                                    -p 8500-8504:8500-8504 \\
                                    --env XH_G_ENV=prod \\
                                    -v /root/server/logs/gateway_log/:/app/logs \\
                                    ${env.IMAGE_TAG}
                                docker logout ${env.REGISTRY_URL}
                            """
                        }
                    }
                }
            }
        }
    }

    post {
        success {
            echo '✅ 构建、推送镜像与部署成功！'
        }
        failure {
            echo '❌ 构建失败，请检查日志。'
        }
    }
}