pipeline { 
    agent {
        label "kaniko"
    }
    stages {
        stage("Checkout") {
            steps {
                checkout scm
                script {
                    env.GIT_COMMIT_SHORT = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
                    env.GIT_AUTHOR_NAME = sh(script: "git log -1 --pretty=format:'%an'", returnStdout: true)
                    env.GIT_AUTHOR_EMAIL = sh(script: "git log -1 --pretty=format:'%ae'", returnStdout: true)
                    env.GIT_COMMIT_MESSAGE = sh (script: 'git log -1 --pretty=%B ${GIT_COMMIT}', returnStdout: true).trim()
                    env.GIT_PROJECT_NAME = GIT_URL.replaceAll('.git$', '').tokenize('/')[-2]
                    env.GIT_REPO_NAME = GIT_URL.replaceAll('.git$', '').tokenize('/')[-1]
                }
            }
        }
        stage("Build") {
            steps {
                container("kaniko") {
                    script {
                        sh "/kaniko/executor --context . --destination registry.kpslp.kr/${GIT_PROJECT_NAME}/${GIT_REPO_NAME}:${GIT_COMMIT_SHORT}"
                    }
                }
            }
        }
        stage("Update Image Tag") {
            steps {
                deleteDir()
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: '*/main']],
                    extensions: [],
                    userRemoteConfigs: [[credentialsId: 'gitlab_userpass_root', url: "https://gitlab.kpslp.kr/root/helm-charts"]]
                ])
                script {
                    def valuesYaml = "kpslp/values_${GIT_REPO_NAME}.yaml"
                    def values = readYaml file: "${valuesYaml}"
                    values.image.tag = env.GIT_COMMIT_SHORT
                    writeYaml file: "${valuesYaml}", data: values, overwrite: true

                    sh "git config user.name '${GIT_AUTHOR_NAME}'"
                    sh "git config user.email '${GIT_AUTHOR_EMAIL}'"
                    withCredentials([usernameColonPassword(credentialsId: 'gitlab_userpass_root', variable: 'USERPASS')]) {
                        sh '''
                        git add . && \
                        git commit -m "${GIT_REPO_NAME}: ${GIT_COMMIT_MESSAGE}" && \
                        git push https://${USERPASS}@gitlab.kpslp.kr/root/helm-charts HEAD:main || true
                        '''
                    }
                }
            }
        }
    }
}
