@Library('infraLib') _

pipeline {
  agent {
    label 'linux-agents-xlarge'
  }
  options {
    timeout(time: 20, unit: 'MINUTES')
    ansiColor('xterm')
  }
  environment {
    NOTIFICATIONS_CHANNEL = 'delphi-etl-cicd-alerts'
  }
  parameters {
    booleanParam(
      defaultValue: true,
      description: "Publish artifact to nexus repository",
      name: 'PUBLISH_ARTIFACT'
    )
  }
  stages {
    stage('Docker login') {
      environment { AWS_PROFILE="gdb-delphi-dev" }
      steps {
        sh '$(aws ecr get-login --no-include-email --region us-east-1)'
      }
    }
    stage('Set Maven credentials') {
      steps {
        script {
          nexus.generateAuthorizedMavenConfig("./.credentials")
        }
      }
    }
    stage('Docker stage') {
      agent {
        docker {
          image '475275892927.dkr.ecr.us-east-1.amazonaws.com/sbt:1.3.3'
          // The following args are aimed to workaround some issues with using Docker container as a Jenkins agent:
          // 1. Disable image entrypoint to let Jenkins verify container was started correctly using custom commands.
          // 2. Explicitly tell SBT locations for configs and local cache because Jenkins runs container using a
          //    custom user (with `-u 1000:1000`) and SBT cannot resolve these paths automatically.
          // 3. Set MaxMetaspaceSize to 1G due to OOM
          args '--entrypoint "" -e JAVA_OPTS="-Dsbt.color=false -Dsbt.global.base=.sbt -Dsbt.boot.directory=.sbt -Dsbt.ivy.home=.ivy2"'
          reuseNode true
        }
      }
      stages {
        stage('Export SBT Settings') {
          steps {
            script {
              env.BUILD_VERSION = sh(
                script: "sbt 'inspect actual version' | grep 'Setting: java.lang.String' | cut -d '=' -f2 | tr -d ' ' | tr -d '[:space:]'",
                returnStdout: true
              )
            }
          }
        }
        stage('Code Style') {
          steps { sh 'sbt validate' }
        }

        stage('Test') {
          steps { sh 'sbt coverage test' }
        }

        stage("Coverage") {
          steps { sh 'sbt coverageAggregate' }
        }

        stage('Publish') {
          when {
            expression { params.PUBLISH_ARTIFACT }
            // publish only for `master` and `develop`
            anyOf {
              branch 'master'
              allOf {
                // publish SNAPSHOT versions from the `develop`
                branch 'develop'
                expression { env.BUILD_VERSION ==~ /.*-SNAPSHOT$/ }
              }
            }
          }
          steps { sh 'sbt publish' }
        }
      }

      post {
        always {
          junit '**/target/test-reports/*.xml'

          recordIssues(
            enabledForFailure: false,
            tool: scala()
          )

          recordIssues(
            enabledForFailure: true,
            tool: checkStyle(pattern: '**/target/scalastyle-result.xml')
          )
        }

        success {
          step([
            $class: 'ScoveragePublisher',
            reportDir: 'target/scala-2.12/scoverage-report',
            reportFile: 'scoverage.xml']
          )
        }
      }
    }

    stage('Git Tag') {
      when {
        branch 'master'
        expression {
            sshagent(['theorchard-ci-ssh-key']) {
                !sh(returnStdout: true, script: "git ls-remote origin refs/tags/v${env.BUILD_VERSION}")?.trim()
            }
        }
      }
      steps {
          sshagent(['theorchard-ci-ssh-key']) {
            sh "git tag v${env.BUILD_VERSION}"
            sh 'git push --tags'
          }
      }
    }

  }
  post {
    unsuccessful {
      script {
        utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
      }
    }
    success {
      script {
        // run only for `develop`
        if (env.BRANCH_NAME == 'develop') {
          build job: "Delphi-projects/pipelines/delphi-etl-apps/${env.BRANCH_NAME}", parameters: [], propagate: false, wait: false
          build job: "Delphi-projects/pipelines/delphi-etl-mapping/${env.BRANCH_NAME}", parameters: [], propagate: false, wait: false
          build job: "Delphi-projects/pipelines/delphi-etl-conversion/${env.BRANCH_NAME}", parameters: [], propagate: false, wait: false
        }
      }
    }
  }
}
