@Library('GlobalJenkinsLibraryNew') _

def cdkDeployAccount = [
    'poc': '615817712084',
    'dev': '030215556060',
    'uat': '534745294648',
    'prd': '022438277857',
]

def credentialsIDs = [
  'poc' : 'ProductDesign Jenkins Deployment POC',
  'dev' : 'digital-creation Development Jenkins Deployment',
  'uat' : 'digital-creation UAT Jenkins Deployment',
  'prd' : 'digital-creation PRD Jenkins Deployment',
]

def mccDatabasePassword = [
  'poc': 'MCC_POC_DATABASE_PASSWORD',
  'dev': 'MCC_DEV_DATABASE_PASSWORD',
  'uat': 'MCC_UAT_DATABASE_PASSWORD',
  'prd': 'MCC_PRD_DATABASE_PASSWORD',
]

def mccSecretKey = [
  'poc': 'MCC_SECRET_KEY',
  'dev': 'MCC_SECRET_KEY',
  'uat': 'MCC_SECRET_KEY',
  'prd': 'MCC_SECRET_KEY',
]

def mccDatabase = [
  'poc': 'devmccmccdb-devmccmccdbwriterfe3d6e74-nzeetdanw6sx.c8uwkt51amck.eu-west-1.rds.amazonaws.com/mccdb',
  'dev': 'dev-mld-mccdb.cluster-c8uwkt51amck.eu-west-1.rds.amazonaws.com/mccdb',
  'uat': 'devmccmccdb-devmccmccdbwriterfe3d6e74-nzeetdanw6sx.c8uwkt51amck.eu-west-1.rds.amazonaws.com/mccdb',
  'prd': 'devmccmccdb-devmccmccdbwriterfe3d6e74-nzeetdanw6sx.c8uwkt51amck.eu-west-1.rds.amazonaws.com/mccdb',
]

def stageChoices = ['poc', 'dev', 'uat']
if (env.BRANCH_NAME == 'main' || env.BRANCH_NAME == 'master') {
  stageChoices = ['poc', 'dev', 'uat', 'prd']
}

def now = new Date()

pipeline {
  environment {
    DEPLOY_ENV = "${params.STAGE}"
    HOME = "${WORKSPACE}"
    CDK_HOME = "${WORKSPACE}"
    CDK_DEPLOY_ACCOUNT = "${cdkDeployAccount[DEPLOY_ENV]}"
    CDK_DEPLOY_REGION = 'eu-west-1'
    CDK_QUALIFIER = "${DEPLOY_ENV}-mld"
    STACK_NAME = 'MoldCostCalc'
    POSTGRES_USER = 'mccAdmin'
    POSTGRES_PASSWORD_ENV = "${mccDatabasePassword[DEPLOY_ENV]}"
    FLASK_APP = 'run.py'
    FLASK_ENV = 'production'
    HOST_ENV = 'AWS'
    SECRET_KEY_ENV = "${mccSecretKey[DEPLOY_ENV]}"
  }

  agent {
    label 'ubuntu_node-20_docker-20'
  }

  parameters {
    choice(name: 'ACTION', choices: ['Analysis', 'Deploy'], description: 'Deployment Type')
    choice(name: 'STAGE', choices: stageChoices, description: 'Environment to deploy. Must match with the value in CDK.JSON context')
  }

  options {
    disableConcurrentBuilds()
    parallelsAlwaysFailFast()
    timestamps()
    buildDiscarder(logRotator(numToKeepStr: '3'))
  }

  stages {
    stage('Deploy') {
      when {
        expression { return params.ACTION == 'Deploy' }
      }
      steps {
        dir('infra') {
            withCredentials([
              string(credentialsId: "${POSTGRES_PASSWORD_ENV}", variable: 'POSTGRES_PASSWORD'),
              string(credentialsId: "${SECRET_KEY_ENV}", variable: 'SECRET_KEY'),
              aws(credentialsId: credentialsIDs[env.DEPLOY_ENV], accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')
              ]) {
              script {
                env.DATABASE_URL = "postgresql://${env.POSTGRES_USER}:${env.POSTGRES_PASSWORD}@${mccDatabase[env.DEPLOY_ENV]}"
              }
              withNvm {
                sh 'npm install'
                sh "npx aws-cdk@2.1019.1 bootstrap aws://${env.CDK_DEPLOY_ACCOUNT}/${env.CDK_DEPLOY_REGION} --context config=${env.DEPLOY_ENV} --toolkit-stack-name ${env.DEPLOY_ENV}${env.STACK_NAME} --change-set-name changeset-${env.DEPLOY_ENV}-${currentBuild.number} --qualifier ${env.CDK_QUALIFIER}"
                sh "npx aws-cdk@2.1019.1 deploy --all --context config=${env.DEPLOY_ENV} --toolkit-stack-name ${env.DEPLOY_ENV}${env.STACK_NAME} --change-set-name ${env.STACK_NAME}-changeset-${env.DEPLOY_ENV}-${currentBuild.number} --require-approval never"
              }
              }
        }
      }
    }
  }

  post {
    always {
      cleanWs()
    }
  }
}
