def PIPELINE_ID = "${env.BUILD_NUMBER}"

def getImageTag() {
    def dateFormat = new java.text.SimpleDateFormat('yyyyMMddHHmmss')
    def currentDate = new Date()
    return dateFormat.format(currentDate)
}

podTemplate(
    label: "${PIPELINE_ID}",
    serviceAccount: 'jenkins',
    containers: [
        containerTemplate(name: 'node', 
            image: 'node:20-slim', 
            ttyEnabled: true, 
            command: 'cat'),
        containerTemplate(name: 'podman', 
            image: "mgoltzsche/podman", 
            ttyEnabled: true, 
            command: 'cat', 
            privileged: true),
        containerTemplate(name: 'git', 
            image: 'alpine:3.19', 
            command: 'cat', 
            ttyEnabled: true)
    ],
    volumes: [
        emptyDirVolume(mountPath: '/root/.azure', memory: false)
    ]
) {
    node(PIPELINE_ID) {
        def props
        def imageTag = getImageTag()
        def manifestRepo = 'cna-bootcamp/lifesub-manifest'
        def manifestBranch = 'main'

        stage("Get Source") {
            checkout scm
            props = readProperties file: "deployment/deploy_env_vars"
        }

        stage('Build & Push Image') {
            container('podman') {
                withCredentials([usernamePassword(
                    credentialsId: 'acr-credentials',
                    usernameVariable: 'USERNAME',
                    passwordVariable: 'PASSWORD'
                )]) {
                    def imagePath = "${props.registry}/${props.image_org}/lifesub-web:${imageTag}"
                    
                    sh """
                        podman login ${props.registry} --username \$USERNAME --password \$PASSWORD

                        podman build \\
                            --build-arg PROJECT_FOLDER="." \\
                            --build-arg REACT_APP_MEMBER_URL="${props.react_app_member_url}" \\
                            --build-arg REACT_APP_MYSUB_URL="${props.react_app_mysub_url}" \\
                            --build-arg REACT_APP_RECOMMEND_URL="${props.react_app_recommend_url}" \\
                            --build-arg BUILD_FOLDER="deployment" \\
                            --build-arg EXPORT_PORT="${props.export_port}" \\
                            -f deployment/Dockerfile-lifesub-web \\
                            -t ${imagePath} .
                        
                        podman push ${imagePath}
                    """
                }
            }
        }

        stage('Update Manifest') {
            container('git') {
                // git과 yq 설치
                sh '''
                    apk add --no-cache git curl
                    curl -L https://github.com/mikefarah/yq/releases/download/v4.40.5/yq_linux_amd64 -o /usr/local/bin/yq
                    chmod +x /usr/local/bin/yq
                '''

                withCredentials([usernamePassword(
                    credentialsId: 'github-credentials',
                    usernameVariable: 'GIT_USERNAME',
                    passwordVariable: 'GIT_PASSWORD'
                )]) {
                    sh '''
                        git config --global user.email "jenkins@example.com"
                        git config --global user.name "Jenkins"
                    '''
                    
                    sh """
                        rm -rf lifesub-manifest
                        git clone https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/${manifestRepo}.git
                    """
                    
                    dir('lifesub-manifest') {
                        def imagePath = "${props.registry}/${props.image_org}/lifesub-web:${imageTag}"
                        sh """
                            yq -i '.spec.template.spec.containers[0].image = "${imagePath}"' lifesub-web/deployments/lifesub-web-deployment.yaml
                            
                            git add .
                            git diff-index --quiet HEAD || git commit -m "Update lifesub-web image to ${imageTag}"
                            git push origin ${manifestBranch}
                        """
                    }
                }
            }
        }
    }
}