String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#docker-parent-image-build-alerts'
String ECR_REPO = 'docker-parent-images'

pipeline {
    agent any

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

    parameters {
        string(
            name: 'PROJECT_NAMES',
            defaultValue: '',
            description: 'Comma-separated list of project names to build. Set to * to build all projects.'
        )
        string(
            name: 'SHARED_LIBRARIES_VERSION',
            defaultValue: 'master',
            description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.'
        )
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
        parameterizedCron(env.BRANCH_NAME == 'master' ? 'H 23 * * * %PROJECT_NAMES=*' : '')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Create and Scan a Release') {
            steps {
                script {
                    withSecrets(awsAccountId: '086679231553', awsRole: 'shared-jenkins-docker-hub-role', secrets: [
                        ['id': 'shared/jenkins-docker-hub/DOCKER_HUB_TOKEN', environmentVariable: 'DOCKER_HUB_TOKEN']
                    ]) {
                        // We perform the build, scan and promote steps within the same stage to ensure that a failure for one
                        // project does not prevent subsequent steps from running for other projects.
                        withModifiedProjects(checkout: true) { project ->
                            dockerToEcr awsRegions: AWS_REGIONS,
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: ECR_REPO,
                                imageTag: "${project}.${env.GIT_COMMIT}",
                                dockerBuildContext: "./${project}",
                                dockerBuildFile: "./${project}/Dockerfile",
                                pushLatest: false,
                                registryCredentials: project.contains('hardened') ? [
                                    [username: 'orchardit', password: env.DOCKER_HUB_TOKEN] // We need to authenticate with Docker Hub in order to pull images from the dhi registry
                                ] : []

                            dockerScan awsRegion: AWS_REGIONS[0],
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: ECR_REPO,
                                imageTag: "${project}.${env.GIT_COMMIT}",
                                slackNotificationChannel: env.BRANCH_NAME == 'master' ? SLACK_NOTIFICATIONS_CHANNEL : null

                            if (env.BRANCH_NAME == 'master') {
                                retagEcrImage awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: ECR_REPO,
                                    imageTag: "${project}.${env.GIT_COMMIT}",
                                    newTag: project
                            }
                        }
                    }
                }
            }
        }
    }
    post {
        failure {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
    }
}

def withModifiedProjects(Map args = [:], Closure steps) {
    getMonorepoUtils().withModifiedProjects(args, steps)
}

def getMonorepoUtils() {
    return library("jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}").com.sonymusic.MonorepoUtils.getInstance(
        steps: this,
        projectBasePath: '.',
        projectsToBuild: params.PROJECT_NAMES ? params.PROJECT_NAMES.split(',') : null
    )
}
