#!/usr/bin/env groovy

@Library('infraLib') _

pipeline {
  agent {
    label 'linux-agents'
  }
  options {
    ansiColor('xterm')
    disableConcurrentBuilds()
  }
  environment {
    AWS_PROFILE             = "gdb-delphi-dev"
    PROJECT_GROUP           = "apollo"
    ECR                     = "475275892927.dkr.ecr.us-east-1.amazonaws.com"
    OCTOPUS_CLI_SERVER      = "https://octopus.delphi.zone"
    OCTOPUS_CLI_API_KEY     = utility.getSecretValueById('infra/jenkins/octopus_api_key', env.AWS_PROFILE)
    OCTOPUS_CHANNEL         = octopus.setOctoChannel(env.BRANCH_NAME)
    DEPLOY_ENV              = octopus.setDeploymentEnv(params.DEPLOY_ENV_CHOICE, env.PROJECT_GROUP, env.BRANCH_NAME)
    NOTIFICATIONS_CHANNEL   = '#apollo-deployments'
  }
  parameters {
    choice(
      choices: [
        'default',
        'dev',
        'prod',
        'skip_deployment'
      ],
      description: 'Set environment for deployment.',
      name: 'DEPLOY_ENV_CHOICE'
    )
    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'
    )
  }
  stages {
    stage("Pipeline") {
      steps {
        script {
          def pipelineParams = pythonPackage.setDockerPipelineParams(
            params.IMAGE_UPLOAD_MODE,
            params.SKIP_RELEASE_CREATION,
            '.',
            env.PROJECT_GROUP,
            env.ECR,
            'lambda',
            'apollo.spotify-charts-notifications',
            'spotify-charts-notifications'
          )
          pythonPackage.pythonTestPipeline(pipelineParams)
          // env.CHANGE_ID is present only for PR
          (!env.CHANGE_ID) && pythonPackage.dockerPipeline(pipelineParams)
        }
      }
    }
  }
  post {
    always {
      sh "sudo chown -R ec2-user:ec2-user ${env.WORKSPACE}"
      script {
        utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
      }
    }
    cleanup {
        deleteDir()
    }
  }
}
