/**
 * ACK + Harbor 发版共享函数库（不是 Jenkins 入口文件）。
 *
 * - 单服务：produ/<prodDir>/Jenkinsfile 在顶层 pipeline 内 load 本文件后调用各 stage 函数。
 * - 整体/多选：produ/whole/Jenkinsfile load 本文件 + service-registry.groovy。
 *
 * Harbor：流水线内 docker login / build / push，日常发版无需打开 Harbor Web。
 */

def checkoutBranch(def script, String branch, String gitUrl, String credentialsId) {
    script.git branch: branch, credentialsId: credentialsId, url: gitUrl
    script.sh """
        set -e
        git fetch origin
        git reset --hard origin/${branch}
        git log -1 --oneline
    """
}

def mavenPackageModule(def script, String module) {
    script.sh """
        set -e
        unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
        export MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true"
        mvn -version
        mvn clean package -pl ${module} -am -DskipTests -e \\
            -Dmaven.repo.local=\${WORKSPACE}/.m2/repository
    """
}

/** 整体发版：根 POM 一次打包全部模块（比 7 次单模块 mvn 更快） */
def mavenPackageAll(def script) {
    script.sh """
        set -e
        unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
        export MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true"
        mvn -version
        mvn clean package -DskipTests -e \\
            -Dmaven.repo.local=\${WORKSPACE}/.m2/repository
    """
}

def dockerBuildAndPush(def script, Map cfg) {
    def registry = cfg.harborRegistry
    def project = cfg.harborProject
    def prodDir = cfg.prodDir
    def module = cfg.module
    def serverPort = cfg.serverPort
    def withLib = cfg.withLib ? 'true' : 'false'
    def baseImage = cfg.baseImage
    def imageRef = cfg.imageRef
    def harborCreds = cfg.harborCredentialsId
    def dockerfile = 'docs/jenkins/produ/docker/Dockerfile.java-service'
    def moduleDir = "${script.env.WORKSPACE}/${module}"
    def jarName = "${module}-1.0.0.jar"

    script.withCredentials([script.usernamePassword(
        credentialsId: harborCreds, usernameVariable: 'HARBOR_USER', passwordVariable: 'HARBOR_PASS')]) {
        script.sh """
            set -e
            mkdir -p ${moduleDir}/lib
            touch ${moduleDir}/lib/.keep
            echo "\${HARBOR_PASS}" | docker login ${registry} -u "\${HARBOR_USER}" --password-stdin
            docker build -f ${dockerfile} \\
                --build-arg BASE_IMAGE=${baseImage} \\
                --build-arg JAR_FILE=${jarName} \\
                --build-arg SERVER_PORT=${serverPort} \\
                --build-arg WITH_LIB=${withLib} \\
                -t ${imageRef} \\
                ${moduleDir}
            docker push ${imageRef}
        """
    }
}

def deployToAck(def script, Map cfg) {
    def ns = cfg.k8sNamespace
    def imageRef = cfg.imageRef
    def strategy = cfg.deployStrategy
    def targetDeploy = strategy == 'canary' ? cfg.deploymentCanary : cfg.deploymentStable
    def canaryWeight = cfg.canaryWeight
    def ingressCanary = cfg.ingressCanary
    def kubeCreds = cfg.kubeCredentialsId

    script.withCredentials([script.file(credentialsId: kubeCreds, variable: 'KUBECONFIG')]) {
        script.sh """
            set -e
            kubectl config current-context
            kubectl -n ${ns} set image deployment/${targetDeploy} app=${imageRef} --record
            kubectl -n ${ns} rollout status deployment/${targetDeploy} --timeout=300s
        """
        if (strategy == 'canary') {
            script.sh """
                set -e
                kubectl -n ${ns} annotate ingress ${ingressCanary} \\
                    nginx.ingress.kubernetes.io/canary=true \\
                    nginx.ingress.kubernetes.io/canary-weight=${canaryWeight} \\
                    --overwrite
            """
        }
    }
}

return this
