// ECR repo the backup EC2 cron pulls as `neo4j-cluster-backup:latest` (see backup/README.md).
String IMAGE_NAME = 'neo4j-cluster-backup'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#neo4j-db'

pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Build and Push Image') {
            when {
                branch 'master'
            }
            steps {
                // Builds backup/Dockerfile and pushes both :${GIT_COMMIT} and :latest to ECR.
                // The EC2 backup cron pulls neo4j-cluster-backup:latest, so pushLatest (default true)
                // is what actually deploys the new code on the next 04:15 run.
                // dockerBuildFile is relative to the checkout root (dockerToEcr runs docker build
                // from there), while dockerBuildContext points the build context at backup/.
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: IMAGE_NAME,
                    imageTag: env.GIT_COMMIT, dockerBuildContext: 'backup', dockerBuildFile: 'backup/Dockerfile'
            }
        }
    }

    post {
        regression {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
