def JOB_NAME = "${env.JOB_NAME}"
def BUILD_NUMBER = "${env.BUILD_NUMBER}"
def label = "jenkins-${JOB_NAME}-${BUILD_NUMBER}-${UUID.randomUUID().toString()}"

def code_path = "rpc"
def project_name = "pcm-coordinator-rpc"

podTemplate(label: label, containers: [
    containerTemplate(name: 'golang', image: 'golang:1.20.2-alpine3.17', command: 'cat', ttyEnabled: true),
    containerTemplate(name: 'docker', image: 'docker:latest', command: 'cat', ttyEnabled: true),
    containerTemplate(name: 'kubectl', image: 'jcce/kubectl:1.23.7', command: 'cat', ttyEnabled: true)
], serviceAccount: 'jenkins', volumes: [
    hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]) {
    node(label) {
        // 镜像仓库地址
        // def registryUrl = "registry.cn-hangzhou.aliyuncs.com"
        def imageEndpoint = "jcce/${project_name}"
        stage('拉取代码') {
            checkout scmGit(branches: [[name: "*/${branches}"]], extensions: [], userRemoteConfigs: [[credentialsId: 'gitlink-zj', url: 'https://gitlink.org.cn/JointCloud/pcm-coordinator.git']])
            echo "获取commit_id 作为镜像标签"
            script {
                env.imageTag = sh(returnStdout: true, script: 'git rev-parse --short HEAD').trim()
                env.image = "${registryUrl}/${imageEndpoint}:${imageTag}"
                env.imageLatest = "${registryUrl}/${imageEndpoint}:latest"
            }
        }
//         stage('代码编译打包') {
//             try {
//                 container('golang') {
//                     echo "代码编译打包阶段"
//                     sh """
//                         cd ${code_path}
//                         export GOPROXY=https://goproxy.cn
//                         CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ${project_name} ./pcmcore.go
//                         """
//                 }
//             } catch (exc) {
//                 println "构建失败 - ${currentBuild.fullDisplayName}"
//             }
//         }
        stage('构建 Docker 镜像') {
            withCredentials([[
                $class: 'UsernamePasswordMultiBinding',
                credentialsId: 'docker-auth',
                usernameVariable: 'DOCKER_USER',
                passwordVariable: 'DOCKER_PASSWORD'
            ]]) {
                container('docker') {
                    echo "构建 Docker 镜像阶段"
                    sh """
                        docker login ${registryUrl} -u ${DOCKER_USER} -p ${DOCKER_PASSWORD}
                        docker build -t ${image} -t ${imageLatest} -f ${code_path}/Dockerfile .
                        docker push ${image}
                        docker push ${imageLatest}
                        docker rmi -f ${image} ${imageLatest}
                    """
                }
            }
        }
        stage('运行 Kubectl 部署到k8s平台') {
            withCredentials([file(credentialsId: 'kubeconfig', variable: 'KUBECONFIG')]) {
                container('kubectl') {
                    echo "部署应用"
                    sh """
                        mkdir -p ~/.kube && cp ${KUBECONFIG} ~/.kube/config
                        cd ${code_path}
                        sed -i 's#image_name#${image}#' ${project_name}.yaml
                        sed -i 's#secret_name#${secret_name}#' ${project_name}.yaml
                        sed -i 's#nacos_host#${nacos_host}#' ${project_name}.yaml
                        cat ${project_name}.yaml
                        kubectl apply -f ${project_name}.yaml
                    """
                }
            }
        }
        stage('清理镜像') {
            container('docker') {
                sh  """
                    docker rmi -f ${image} ${imageLatest}
                """
                // cleanWs notFailBuild: true
            }
        }
    }
}