#!groovy

@Library('infraLib') _

def bumpVersionBranch = 'master'

pipeline {
  agent {
    label 'linux-agents'
  }
  options {
    ansiColor('xterm')
    disableConcurrentBuilds()
    timeout(60)
    timestamps()
    buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '30')
  }
  environment {
    PROJECT        = 'gate-api'
    PROJECT_GROUP  = 'apollo'

    AWS_PROFILE    = 'gdb-apollo-dev'
    AWS_ACCOUNT_ID = '725764004555'
    AWS_REGION     = 'us-east-1'

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

    OCTOPUS_PROJECT     = "${env.PROJECT_GROUP}.apollo-gate-api"
    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.setDeploymentEnvV2(params.DEPLOY_ENV_CHOICE, env.PROJECT_GROUP, env.BRANCH_NAME)

    NOTIFICATIONS_CHANNEL = '#apollo-deployments'
  }

  parameters {
    separator(name: 'separator-apollo-gate-api-deployment', sectionHeader: 'Deployment parameters')
    choice(
      choices: [
        'default',
        'dev',
        'test',
        'qa',
        'stage',
        'uat',
        'prod',
        'skip_deployment'
      ],
      description: 'Set environment for deployment.',
      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-apollo-gate-api-checks', sectionHeader: 'Skip static checks')
    booleanParam(name: 'SKIP_TEST', defaultValue: false, description: 'Skip unit tests')
    booleanParam(name: 'SKIP_STATIC', defaultValue: false, description: 'Skip static checks')
  }

  stages {
    stage('Wrapper') {
      when {
        not {
          changelog 'Bump version'
        }
      }
      stages {
        stage('Bump Version') {
          when {
            branch "${bumpVersionBranch}"
          }
          stages {
            stage('Patch') {
              when {
                allOf {
                  not {
                    changelog '#minor'
                  }
                  not {
                    changelog '#major'
                  }
                }
              }
              steps {
                sh 'make version/patch'
              }
            } /** end: stage */

            stage('Minor') {
              when {
                changelog '#minor'
              }
              steps {
                sh 'make version/minor'
              }
            } /** end: stage */

            stage('Major') {
              when {
                changelog '#major'
              }
              steps {
                sh 'make version/major'
              }
            } /** end: stage */
          } /** end: stages */
        } /** end: stage */

        stage('BuildWrapper') {
          environment {
            VERSION = octopus.getVersion(env.BRANCH_NAME,env.WORKSPACE)
          }

          stages {
            stage('Build') {
              options {
                retry(2)
              }
              steps {
                script { currentBuild.displayName = env.VERSION }
                sh label: 'build', script: '''
                    cp .env.sample .env
                    make docker/image/build
                '''
              } /** end: steps */
            } /** end: stage */

            stage('Test') {
              when {
                not {
                  expression { return params.SKIP_TEST }
                }
              }
              steps {
                sh label: 'test', script: '''
                    make docker/test
                '''
              } /** end: steps */
              post {
                always {
                  sh "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
                  junit allowEmptyResults: false, testResults: "report.xml"
                  cobertura autoUpdateHealth: false,
                    autoUpdateStability: false,
                    coberturaReportFile: 'coverage.xml',
                    conditionalCoverageTargets: '98, 70, 70',
                    failUnhealthy: false,
                    failUnstable: false,
                    lineCoverageTargets: '98, 70, 70',
                    maxNumberOfBuilds: 0,
                    methodCoverageTargets: '100, 70, 70',
                    onlyStable: false,
                    zoomCoverageChart: false
                 sh "make docker/clean"
                }
              }
            } /** end: stage */

            stage('Static') {
              when {
                not {
                  expression { return params.SKIP_STATIC }
                }
              }
              parallel {
                stage('Checkstyle') {
                  steps {
                    sh label: 'checkstyle', script: '''
                      make docker/checkstyle
                    '''
                  } /** end: steps */
                  post {
                    always {
                      sh "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
                    }
                  }
                } /** end: stage */
                stage('Security') {
                  steps {
                    sh label: 'check dependencies', script: '''
                      make docker/security
                    '''
                  } /** end: steps */
                  post {
                    always {
                      sh "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
                    }
                  }
                } /** end: stage */
              }
            } /** end: stage */

            stage('Deploy') {
              when {
                anyOf {
                  branch 'master'
                  branch 'production'
                  branch 'release'
                  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/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 */
        } /** end; stage */
      } /** end: stages */
      post {
        success {
          script {
            if (env.BRANCH_NAME.equals(bumpVersionBranch)) {
              sshagent(['dna-ci-rw']) {
                sh """
                    #!/usr/bin/env bash
                    set +x
                    export GIT_SSH_COMMAND="ssh -oStrictHostKeyChecking=no"
                    git push origin HEAD:${env.BRANCH_NAME}
                    git push origin v\$(cat VERSION)
                """
              }
            }
          }
        }
        always {
          sh label: 'fix permissions', script: "sudo chown \$(whoami):\$(whoami) -R ${env.WORKSPACE}"
          sh label: 'shutdown containers', script: 'make docker/clean'
          script {
            utility.slackNotify(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
          }
        }
        cleanup {
          deleteDir()
        }
      } /** end: post */
    } /** end: stage */
  } /** end: stages */
} /* end: pipeline */
