String GITHUB_REPOSITORY = 'lambda-contract-expiration'
List<String> AWS_REGIONS = ['us-east-1']
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String SLACK_NOTIFICATIONS_CHANNEL = '#abacus-devs'

@groovy.transform.Field
List<String> functionsToBuild = null

pipeline {
    agent any

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

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

    parameters {
        booleanParam(name: 'DEPLOY_EXPIRING_CONTRACTS', defaultValue: false, description: 'Deploy expiring_contracts lambda to selected environment.')
        booleanParam(name: 'DEPLOY_MANAGERIGHTS_ENABLE', defaultValue: false, description: 'Deploy managerights_enable lambda to selected environment.')
        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).')
        choice(name: 'DEPLOY_ENVIRONMENT', choices: ['none', 'qa', 'prod'], description: 'Select environment to deploy (none to skip deploy).')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                sh 'make unit-lint-test'
            }
        }
        stage('Static Application Security Tests') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Static App Security Tests for ${functionName}"
                    sastTests(projectDir: "lambda/${functionName}")
                }
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Validating Software Catalog Definition for ${functionName}"
                    datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                }
            }
        }
        stage('Sonar Scan and Analysis') {
            agent any
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${GITHUB_REPOSITORY}"
                    sonarScan project: GITHUB_REPOSITORY, language: 'py', exclusions: 'lambda/**/tests/**'
                }
            }
        }
        stage('Deploy') {
            when {
                allOf {
                    branch 'master'
                    expression { return params.DEPLOY_ENVIRONMENT in ['qa','prod'] }
                }
            }
            steps {
                script {
                    def targetEnv = params.DEPLOY_ENVIRONMENT
                    echo "Deployment requested for environment: ${targetEnv}"
                    if (params.DEPLOY_EXPIRING_CONTRACTS) {
                        build job: 'lambda-contract-expiration-expiring_contracts-deploy', parameters: [
                            [$class: 'StringParameterValue', name: 'GIT_COMMIT', value: env.GIT_COMMIT],
                            [$class: 'StringParameterValue', name: 'Environment', value: targetEnv],
                            [$class: 'StringParameterValue', name: 'SENTRY_DSN', value: 'foo']
                        ]
                        if (targetEnv == 'prod') {
                            datadogSoftwareCatalogPublish(servicePath: 'lambda/expiring_contracts')
                        }
                    } else {
                        echo 'Skipping expiring_contracts deployment (flag not set).'
                    }
                    if (params.DEPLOY_MANAGERIGHTS_ENABLE) {
                        build job: 'lambda-contract-expiration-managerights_enable-deploy', parameters: [
                            [$class: 'StringParameterValue', name: 'GIT_COMMIT', value: env.GIT_COMMIT],
                            [$class: 'StringParameterValue', name: 'Environment', value: targetEnv],
                            [$class: 'StringParameterValue', name: 'SENTRY_DSN', value: 'foo']
                        ]
                        if (targetEnv == 'prod') {
                            datadogSoftwareCatalogPublish(servicePath: 'lambda/managerights_enable')
                        }
                    } else {
                        echo 'Skipping managerights_enable deployment (flag not set).'
                    }
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL, message: "Deployment to ${targetEnv} completed."
                }
            }
        }

    }

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

def withModifiedFunctions(Map args = [:], Closure steps) {
    parallel(getFunctionsToBuild().collectEntries { functionName ->
        return [
            (functionName): {
                node {
                    if (args.checkout?.toBoolean()) {
                        cleanWs()
                        def scmVars = checkout scm
                        // Set SCM vars as environment variables to replicate default checkout functionality
                        scmVars.each { k, v ->
                            env."${k}" = v
                        }
                    }
                    steps(functionName)
                }
            }
        ]
    })
}

def getFunctionsToBuild() {
    if (this.@functionsToBuild != null) {
        return this.@functionsToBuild
    }

    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

    if (lambdaFunctionName) {
        this.@functionsToBuild = [lambdaFunctionName]
    } else {
        node {
            def scmVars = checkout scm
            def lambdaDirectories = findFiles(glob: '**/Dockerfile')
            this.@functionsToBuild = getModifiedFunctions branchName: scmVars.BRANCH_NAME,
                previousSuccessfulCommit: scmVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
                lambdaDirectories: lambdaDirectories
        }
    }

    if (this.@functionsToBuild) {
        currentBuild.description = this.@functionsToBuild.join('<br>')
    }

    return this.@functionsToBuild
}
