pipeline {

    agent {
        label "dev"
    }

    tools {
            nodejs 'node22'
        }

    environment {
        KUBECONFIG = "/var/jenkins_home/.kube/cls-bf654m8u-config"
        PATH = "/var/jenkins_home/docker-cli/bin:/var/jenkins_home/kubectl/bin:${env.PATH}"
        BUILD_IMAGE = "${sh(script:'echo -n atyou-prod:h5-$(date +%Y%m%dv%H%M%S)', returnStdout: true)}"
        ALIYUN_REGISTRY = "tuokemi-con-registry.ap-southeast-1.cr.aliyuncs.com/atyou-prod/h5"
        IMAGE_REP_TAG = ""
        K8S_NAMESPACE = "prod"
        K8S_DEPLOYMENT = "h5"
        K8S_APP_LABEL = "h5"
        DOCKER_FILE = "Dockerfile-dev"
    }

    stages {
        stage('Build') {
            steps {
                sh 'export PATH=$HOME/bin:$PATH && export NODE_HOME=/usr/local/node && export PATH=$NODE_HOME/bin:$PATH && npm config set registry https://registry.npmmirror.com && npm install'
                sh 'export PATH=$HOME/bin:$PATH && export NODE_HOME=/usr/local/node && export PATH=$NODE_HOME/bin:$PATH && npm run build:atu-prod'
                sh 'du -sh dist'
                script {
                    IMAGE_REP_TAG = "${ALIYUN_REGISTRY}:h5-${sh(script:'date +%Y%m%dv%H%M%S', returnStdout: true).trim()}"
                }
                echo "---> Image registry tag: ${IMAGE_REP_TAG}"
            }
        }
        stage('Build image') {
            steps {
                withCredentials([usernamePassword(
                    credentialsId: 'aliyun-registry',
                    usernameVariable: 'ALIYUN_USER',
                    passwordVariable: 'ALIYUN_PASS'
                )]) {
                    sh 'echo $ALIYUN_PASS | docker login --username $ALIYUN_USER --password-stdin tuokemi-con-registry.ap-southeast-1.cr.aliyuncs.com'
                }
                sh "docker build -f ${DOCKER_FILE} -t ${IMAGE_REP_TAG} ."
            }
        }
        stage('Upload image') {
            steps {
                sh "docker push ${IMAGE_REP_TAG}"
                sh "docker tag ${IMAGE_REP_TAG} ${ALIYUN_REGISTRY}:latest"
                sh "docker push ${ALIYUN_REGISTRY}:latest"
                sh "docker rmi -f ${IMAGE_REP_TAG} ${ALIYUN_REGISTRY}:latest"
            }
        }
        stage('Apply') {
            steps {
                sh "kubectl -n ${K8S_NAMESPACE} set image deployment/${K8S_DEPLOYMENT} ${K8S_APP_LABEL}=${IMAGE_REP_TAG}"
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}
