@Library('infraLib') _

pipeline {
  agent {
    label 'linux-agents'
  }
  options { disableConcurrentBuilds() }
  environment {
    NOTIFICATIONS_CHANNEL   = 'delphi-slz-cicd-alerts'
  }
  parameters {
    booleanParam(name: 'DEPLOY_TO_DEV', defaultValue: true, description: 'Whether or not to deploy to dev.')
    booleanParam(name: 'DEPLOY_TO_QA', defaultValue: true, description: 'Whether or not to deploy to qa.')
    booleanParam(name: 'DEPLOY_TO_STAGING', defaultValue: false, description: 'Whether or not to deploy to staging.')
    booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: false, description: 'Whether or not to deploy to prod.')
  }
  stages {    
    stage('Deploy to dev') {
      when {
        expression { params.DEPLOY_TO_DEV == true }
      }
      steps {
        script {
          deployToEnv('dev', 'schemas', 'schemas')
        }
      }
    }
    stage('Deploy to QA') {
      when {
        expression { params.DEPLOY_TO_QA == true }
      }
      steps {
        script {
          deployToEnv('qa', 'schemas', 'schemas')
        }
      }
    }
    stage('Deploy to staging') {
      when {
        allOf {
          branch 'master'
          expression { params.DEPLOY_TO_STAGING == true }
        }
      }
      steps {
        script {
          deployToEnv('stage', 'schemas', 'schemas')
        }
      }
    }
    stage('Deploy to prod') {
      when {
        allOf {
          branch 'master'
          expression { params.DEPLOY_TO_PROD == true }
        }
      }
      steps {
        script {
          deployToEnv('prod', 'schemas', 'schemas')
        }
      }
    }
  }
  post {
    always {
      sh "sudo chown -R ec2-user:ec2-user ${env.WORKSPACE}"
    }
    failure {
      script {
        utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
      }
    }
    cleanup {
      deleteDir()
    }
  }
}

def deployToEnv(environment, source, destination) {
  def aws_profile = 'gdb-delphi-dev'
  if (environment == 'prod') {
    aws_profile = 'gdb-delphi-prod'
  }
  def bucket = "${environment}-delphi-configs"
  sh(script: "aws s3 cp --profile ${aws_profile} --recursive ${source} s3://${bucket}/${destination}")
}
