/**
 * gateway：仅晋升 Harbor 镜像 + 可选 ACK。
 * Job：Gateway-K8s | Script Path: docs/jenkins/produ/gateway/Jenkinsfile
 *
 * 与 Job「轻量级检出」配合：不拉 alien-* 业务源码，仅稀疏拉取 _shared 后 load。
 */
def SVC = [prodDir: 'gateway', deployName: 'gateway']

/** 稀疏检出流水线共享库（勿拉全仓业务代码） */
def sparseCheckoutProduShared() {
    checkout scm: [
        $class: 'GitSCM',
        branches: scm.branches,
        extensions: [
            [$class: 'CloneOption', depth: 1, shallow: true, noTags: true],
            [$class: 'SparseCheckoutPaths', sparseCheckoutPaths: [
                [path: 'docs/jenkins/produ/_shared/'],
            ]],
        ],
        userRemoteConfigs: scm.userRemoteConfigs,
    ]
}

pipeline {
    agent any
    options {
        buildDiscarder(logRotator(numToKeepStr: '15'))
        timestamps()
        timeout(time: 45, unit: 'MINUTES')
    }
    parameters {
        string(name: 'SOURCE_TAG', defaultValue: 'uat-latest', trim: true,
            description: 'Harbor UAT tag，默认 uat-latest；回滚填 uat-build-<N>')
        string(name: 'TARGET_TAG', defaultValue: '', trim: true,
            description: '留空则 produ-${BUILD_NUMBER}')
        string(name: 'HARBOR_REGISTRY', defaultValue: '39.105.153.68', trim: true)
        string(name: 'HARBOR_PROJECT', defaultValue: 'alien_cloud', trim: true)
        choice(name: 'PROMOTE_METHOD', choices: ['harbor-api', 'docker-pull'],
            description: 'harbor-api=服务端打 tag（快，默认）')
        choice(name: 'DEPLOY_STRATEGY', choices: ['rolling', 'canary', 'skip'],
            description: '''rolling=更新 stable Deployment，kubectl 滚动替换 Pod（全量发版）
canary=仅更新 *-canary Deployment，并按 CANARY_WEIGHT 设置 Ingress 灰度流量
skip=只晋升 Harbor 镜像，不执行 kubectl''')
        string(name: 'CANARY_WEIGHT', defaultValue: '10', trim: true)
        string(name: 'K8S_NAMESPACE', defaultValue: 'alien-produ', trim: true)
        booleanParam(name: 'DRY_RUN', defaultValue: false)
    }
    environment {
        HARBOR_CREDENTIALS = 'harbor-robot-alien'
        KUBECONFIG_CREDENTIALS = 'ack-kubeconfig-alien'
    }
    stages {
        stage('Promote image & Deploy ACK') {
            steps {
                script {
                    sparseCheckoutProduShared()
                    def k8s = load 'docs/jenkins/produ/_shared/k8s-produ-lib.groovy'
                    k8s.promoteOneServiceToAck(this, SVC)
                    echo ">>> gateway 完成: ${env.IMAGE_REF}"
                }
            }
        }
    }
}
