pipeline {

    agent {
        label "prod"
    }

    environment {
        BUILD_IMAGE = "${sh(script:'echo -n halar:page-console-$(date +%Y%m%dv%H%M%S)', returnStdout: true)}"
        IMAGE_REP_TAG = "794038239327.dkr.ecr.ap-southeast-1.amazonaws.com/"
        K8S_NAMESPACE = "prod-hooka"
        K8S_DEPLOYMENT = "console-page"
        K8S_APP_LABEL = "console-page"
    }

    stages {
        stage('Build') {
            steps {
                sh 'export PATH=$HOME/bin:$PATH &&export NODE_HOME=/usr/local/node &&export PATH=$NODE_HOME/bin:$PATH &&export PATH=$PATH:/usr/local/go/bin && npm install'
                sh 'export PATH=$HOME/bin:$PATH &&export NODE_HOME=/usr/local/node &&export PATH=$NODE_HOME/bin:$PATH &&export PATH=$PATH:/usr/local/go/bin && npm run build:prod'
                sh 'du -sh dist'
                script {
                  IMAGE_REP_TAG="${sh(script:'echo -n ${IMAGE_REP_TAG}${BUILD_IMAGE}', returnStdout: true)}"
                }
            }
        }
        stage('Build image') {
            steps {
                sh "aws ecr get-login-password --region ap-southeast-1 | docker login --username AWS --password-stdin 794038239327.dkr.ecr.ap-southeast-1.amazonaws.com"
                sh "docker build -t ${BUILD_IMAGE} . -f Dockerfile-hooka"
            }
        }
        stage('Upload image') {
            steps {
                sh "docker tag ${BUILD_IMAGE} ${IMAGE_REP_TAG}"
                sh "docker push ${IMAGE_REP_TAG}"
                sh "docker rmi -f ${BUILD_IMAGE} ${IMAGE_REP_TAG}"
            }
        }
        stage('Apply') {
            steps {
                sh "kubectl -n ${K8S_NAMESPACE} set image deployment/${K8S_DEPLOYMENT} ${K8S_APP_LABEL}=${IMAGE_REP_TAG} --kubeconfig=/data/kube/hooka-config"
            }
        }

        
    }
    post {
        always {
            cleanWs()
        }
    }
}
