String SLACK_NOTIFICATIONS_CHANNEL = '#devops-internal-alerts'

pipeline {
    agent none

    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 or Git revision.')
        string(name: 'PROJECTS', defaultValue: '', description: "Comma-separated list of projects to build. If not specified, all modified projects will be built")
    }

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

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                withModifiedProjects(checkout: true) { project, config ->
                    dir(project) {
                        complianceChecks()
                    }
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                withModifiedProjects(checkout: true) { project, config ->
                    dir(project) {
                        sastTests()
                    }
                }
            }
        }
        stage('Validate Software Catalog Definitions') {
            steps {
                withModifiedProjects(checkout: true) { project, config ->
                    datadogSoftwareCatalogValidate(servicePath: "services/${project}")
                }
            }
        }
        // TODO: Add stages to build and deploy each service
        stage('Publish Software Catalog Definitions') {
            when {
                allOf {
                    branch 'master'
                }
            }
            steps {
                withModifiedProjects(checkout: true) { project, config ->
                    datadogSoftwareCatalogPublish(servicePath: "services/${project}")
                }
            }
        }
    }

    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
                }
            }
        }
    }
}

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: 'services',
        projectsToBuild: params.PROJECTS ? params.PROJECTS.split(',') : null,
    )
}
