@Library('infraLib') _

pipeline {
    agent {
        label 'linux-agents'
    }

    options {
        timeout(time: 10, unit: 'MINUTES')
        ansiColor('xterm')
    }

    environment {
        PROJECT_GROUP = "delphi"
        NOTIFICATIONS_CHANNEL = 'delphi-etl-cicd-alerts'
        GIT_SSH_COMMAND = "ssh -oStrictHostKeyChecking=no"
    }

    parameters {
        choice(
            choices: [
                'yes',
                'no'
            ],
            description: "Publish artifact to nexus repository",
            name: 'PUBLISH_ARTIFACT'
        )
    }

    stages {
        stage('Lint') {
            steps {
                sh 'docker run -v "$(pwd):/work" uber/prototool:latest prototool lint'
            }
        }

        stage('Break Check') {
            when {
                changeRequest()
            }
            steps {
                sshagent(['theorchard-ci-ssh-key']) {
                    sh 'git fetch origin $CHANGE_TARGET:$CHANGE_TARGET'
                    sh 'docker run -v "$(pwd):/work" uber/prototool:latest prototool break check --git-branch $CHANGE_TARGET'
                }
            }
        }

        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') {
            when {
                changeset "src/**"
            }
            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('Version') {
                    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('Build') {
                    steps { sh 'sbt +compile' }
                }

                stage('Publish') {
                    when {
                        expression { params.PUBLISH_ARTIFACT == 'yes' }
                        branch 'master'
                    }
                    steps {
                        sh 'sbt +publish'
                    }
                }

            }
        }

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

    post {
        failure {
            script {
                utility.slackNotifyMainBranches(currentBuild.currentResult, env.NOTIFICATIONS_CHANNEL)
            }
        }
    }
}
