pipeline {

    agent {
      label "dev"
    }

    environment {
        BUILD_IMAGE = "${sh(script:'echo -n likei-dev:page-console-$(date +%Y%m%dv%H%M%S)', returnStdout: true)}"
        IMAGE_REP_TAG = "989328288674.dkr.ecr.ap-southeast-1.amazonaws.com/"
        K8S_NAMESPACE = "local"
        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:stage'
                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 989328288674.dkr.ecr.ap-southeast-1.amazonaws.com"
                sh "docker build -t ${BUILD_IMAGE} ."
            }
        }
        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}"
            }
        }

    //    stage('Clear Cahe') {
    //       steps {
    //            sh 'sleep 40s'
    //           sh 'aws cloudfront create-invalidation --distribution-id E3PFTQHTUMCCVT  --paths "/*"'
    //        }
    //    }
    }
     post {
         always {
             cleanWs()
         }
     }
}
