#!/usr/bin/env groovy

@Library('infraLib') _

def getAuth0DomainByBranch(branch) {
  if (branch.equals('master')) {
    return 'prod-dna-apps.auth0.com'
  }
  return 'sme-dna.auth0.com'
}

def getAuth0ClientIdByBranch(branch) {
  if (branch.equals('master')) {
    return '4Iq0lOL3TZH8lQ1vb1wn6Ait09XnZWBc'
  }
  return 'CAmEb2ywkISejwPIekEyuEiqD2U4a6IS'
}

def getAuth0AudienceByBranch(branch) {
  if (branch.equals('master')) {
    return 'https://api.sma.stream'
  }
  return 'https://dev-api.sma.stream'
}

def getApiUrlByBranch(branch) {
  if (branch.equals('master')) {
    return 'https://api.insights.stream'
  }
  return 'https://dev-api.insights.stream'
}

def getAmplitudeApiKeyByBranch(branch) {
  if (branch.equals('master')) {
    return '41548f43eb175cb6f1d2211e91084a42'
  }
  return '94e2a81a95b37790d6d6fc11e9444738'
}

pipeline {
  agent {
    label 'linux-agents'
  }
  options {
    ansiColor('xterm')
    disableConcurrentBuilds()
    timeout(60)
    timestamps()
    buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '30')
  }
  environment {
    PROJECT       = 'amadeus'
    PROJECT_GROUP = 'rti'
    VERSION       = octopus.getVersion(env.BRANCH_NAME, env.WORKSPACE)

    AWS_REGION          = 'us-east-1'
    ECR_REPOSITORY_NAME = "${env.PROJECT_GROUP}/${env.PROJECT}"

    AWS_PROFILE    = 'gdb-artistapp-dev'
    AWS_ACCOUNT_ID = '714609459574'

    ECR_REGISTRY     = "${env.AWS_ACCOUNT_ID}.dkr.ecr.${env.AWS_REGION}.amazonaws.com"
    ECR_REGISTRY_URI = "${env.ECR_REGISTRY}/${ECR_REPOSITORY_NAME}"

    OCTOPUS_PROJECT     = "${env.PROJECT_GROUP}.${env.PROJECT}"
    OCTOPUS_CLI_SERVER  = 'https://octopus.delphi.zone'
    OCTOPUS_CLI_API_KEY = utility.getSecretValueById('infra/jenkins/octopus_api_key', 'gdb-delphi-dev')
    OCTOPUS_CHANNEL     = octopus.setOctoChannel(env.BRANCH_NAME)
    DEPLOY_ENV          = octopus.setDeploymentEnv(params.DEPLOY_ENV_CHOICE, "artistapp", env.BRANCH_NAME)

    REACT_APP_AUTH0_DOMAIN      = getAuth0DomainByBranch(env.BRANCH_NAME)
    REACT_APP_AUTH0_CLIENT_ID   = getAuth0ClientIdByBranch(env.BRANCH_NAME)
    REACT_APP_AUTH0_AUDIENCE    = getAuth0AudienceByBranch(env.BRANCH_NAME)
    REACT_APP_RTI_API_URL       = getApiUrlByBranch(env.BRANCH_NAME)
    REACT_APP_AMPLITUDE_API_KEY = getAmplitudeApiKeyByBranch(env.BRANCH_NAME)

    NOTIFICATIONS_CHANNEL = '#ama-deployments'
  }
  parameters {
    separator(name: 'separator-amadeus-deployment', sectionHeader: 'Deployment parameters')
    choice(
      choices: [
        'default',
        'dev',
        'prod',
        'skip_deployment'
      ],
      description: 'Set environment for deployment. Development by default',
      name: 'DEPLOY_ENV_CHOICE'
    )
    choice(
      choices: [
        'default',
        'yes',
        'no'
      ],
      description: 'By default deploy is only triggered for develop/release/master branch',
      name: 'TRIGGER_DEPLOY'
    )
    choice(
      choices: [
        'error',
        'overwrite',
        'skip_build'
      ],
      description: "Docker image upload mode - ovewrite if the image with such tag already exists, raise error if exists, or skip build part if exists.",
      name: 'IMAGE_UPLOAD_MODE'
    )
    choice(
      choices: [
        'no',
        'yes'
      ],
      description: "Don't raise errors in case release already exists",
      name: 'SKIP_RELEASE_CREATION'
    )
    separator(name: 'separator-amadeus-checks', sectionHeader: 'Skip static checks')
    booleanParam(name: 'SKIP_TEST', defaultValue: false, description: 'Skip unit tests')
  }
  stages {
    stage('Build') {
      steps {
        script { currentBuild.displayName = env.VERSION }
        sh label: 'build', script: '''
            make docker/login
            make docker/image/build
        '''
      } /** end: steps */
    } /** end: stage */
    stage('Test') {
      when {
        not {
          expression { return params.SKIP_TEST }
        }
      }
      steps {
        sh label: 'test', script: '''
            make docker/login
            make test || exit 0 # TODO: suppress error for now
        '''
      } /** end: steps */
      post {
        always {
          sh "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
        }
      }
    } /** end: stage */
    stage('Deploy') {
      when {
        anyOf {
          branch 'master'
          branch 'develop'
          expression { return params.TRIGGER_DEPLOY.equals('yes') }
        }
      }
      stages {
        stage('Check version') {
          when {
            expression { return params.IMAGE_UPLOAD_MODE == 'error' && octopus.ecrImageTagExists(env.VERSION, env.ECR_REPOSITORY_NAME, env.AWS_PROFILE) }
          }
          steps { error "Image with ${env.VERSION} version tag already exists. To ignore this error set IMAGE_UPLOAD_MODE parameter to overwrite or skip_build" }
        } /** end: stage */
        stage('Push to ECR') {
          when {
            expression { return params.IMAGE_UPLOAD_MODE == 'overwrite' || !octopus.ecrImageTagExists(env.VERSION, env.ECR_REPOSITORY_NAME, env.AWS_PROFILE) }
          }
          steps {
            sh label: 'push', script: '''
              make docker/login
              make docker/image/push
            '''
          } /** end: steps */
        } /** end: stage */
        stage('Create a release in octopus') {
          //Check if release already exists. If it does, raise error or skip it, based on given param
          when {
            expression { return params.SKIP_RELEASE_CREATION.equals('no') || !octopus.releaseExists(env.OCTOPUS_PROJECT, env.VERSION) }
          }
          steps {
            echo octopus.createRelease(env.OCTOPUS_PROJECT, env.VERSION, env.OCTOPUS_CHANNEL)
          } /** end: steps */
        } /** end: stage */
        stage('Deploy release in octopus') {
          when {
            not { expression { return env.DEPLOY_ENV.equals('skip_deployment') } }
          }
          steps {
            echo octopus.deployRelease(env.OCTOPUS_PROJECT, env.DEPLOY_ENV, env.VERSION, env.OCTOPUS_CHANNEL)
          } /** end: steps */
        } /** end: stage */
      } /** end: stages */
    } /** end: stage */
  } /** end: stages */
  post {
    always {
      script {
        utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
      }
    }
    cleanup {
      deleteDir()
    }
  } /** end: post */
}
