String SLACK_NOTIFICATIONS_CHANNEL = '#moneyhub-alerts'

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('Validate Software Catalog') {
            steps {
                script {
                    def lambdaFunctions = [
                        'delete-invalid-attachments',
                        'remove-dynamodb-item',
                        'send-email-on-fail',
                        'store-dynamodb-item-on-fail',
                        'store-dynamodb-item-on-success',
                        'verification'
                    ]
                    lambdaFunctions.each { functionName ->
                        dir("lambda/${functionName}") {
                            datadogSoftwareCatalogValidate()
                        }
                    }
                }
            }
        }
        stage('Publish Software Catalog') {
            when {
                branch 'master'
            }
            steps {
                script {
                    def lambdaFunctions = [
                        'delete-invalid-attachments',
                        'remove-dynamodb-item',
                        'send-email-on-fail',
                        'store-dynamodb-item-on-fail',
                        'store-dynamodb-item-on-success',
                        'verification'
                    ]
                    lambdaFunctions.each { functionName ->
                        dir("lambda/${functionName}") {
                            datadogSoftwareCatalogPublish()
                        }
                    }
                }
            }
        }
    }

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