String GITHUB_REPOSITORY = 'lambda-aws-break-glass'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#devops-internal-alerts'
List<String> VULNERABILITIES_TO_IGNORE = []

def deploymentTargets = [
    'prod': [
        'accountId': '437795906767',
        'deploymentRole': 'prod-jenkins-aws-pipeline-agent'
    ],
    'dev': [
        'accountId': '103233932089',
        'deploymentRole': 'dev-jenkins-pipeline-access-role'
    ],
]

def functionMap = [
    'aws_break_glass_audit',
    'aws_break_glass_cleanup',
    'aws_break_glass_elevate_permissions',
    'aws_break_glass_home_page',
]

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

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_PR_TO_DEV', defaultValue: false, description: 'Whether or not to deploy PR to dev.')
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'LAMBDA_FUNCTION_NAME', defaultValue: '', description: 'Name of the Lambda function to build and deploy')
        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('Get Functions to Build') {
            steps {
                script {
                    getFunctionsToBuild()
                }
            }
        }

        stage('Compliance Checks') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Compliance Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    complianceChecks()
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Validate Software Catalog Definitions') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')
                        return [
                            (functionName): {
                                echo "Validating Software Catalog definition for ${functionName}"
                                datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Unit Tests and Style Checks for ${functionName}"
                                withEcr {
                                    dir("lambda/${functionName}") {
                                        sh 'docker compose run --rm --build lint-and-test'
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Static App Security Tests for ${functionName}"
                                sastTests(projectDir: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${GITHUB_REPOSITORY}"
                    sonarScan project: GITHUB_REPOSITORY, language: 'py'
                }
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { pullRequest.labels.contains('build docker') }
                    expression { params.DEPLOY_PR_TO_DEV }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        // Apply name standardization
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')

                        return [
                            (functionName): {
                                echo "Building for ${functionName}"
                                dockerToEcr awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: "lambda-${sanitizedFunctionName}",
                                    imageTag: env.GIT_COMMIT,
                                    dockerBuildContext: "lambda/${functionName}",
                                    dockerBuildFile: "lambda/${functionName}/Dockerfile"
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to Dev') {
            when {
                anyOf {
                    branch 'master'
                    expression { params.DEPLOY_PR_TO_DEV }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->

                        // Apply name standardization
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')
                        def stageEnv = 'dev'

                        return [
                            (functionName): {
                                echo "Deploying to ${stageEnv.toUpperCase()} for ${functionName}"
                                dir("lambda/${functionName}") {
                                    lambdaDeploy environment: stageEnv,
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "lambda-${sanitizedFunctionName}",
                                        functionName: "${stageEnv}-${sanitizedFunctionName}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: deploymentTargets[stageEnv].accountId,
                                        awsDeploymentRoleName: deploymentTargets[stageEnv].deploymentRole

                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        // Apply name standardization
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')

                        return [
                            (functionName): {
                                echo "Scanning Docker Images for ${functionName}"
                                dir("lambda/${functionName}") {
                                    dockerScan awsRegion: AWS_REGIONS[0],
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: "lambda-${sanitizedFunctionName}",
                                        imageTag: env.GIT_COMMIT,
                                        vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                                }
                            }
                        ]
                    })
                }
            }
        }
        /* No integration tests at the moment
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                script {
                    for (job in getFunctionsToBuild()) {}
                }
            }
        } */

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        // Apply name standardization
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')
                        def stageEnv = 'prod'

                        return [
                            (functionName): {
                                echo "Deploying to ${stageEnv.toUpperCase()} for ${functionName}"
                                dir("lambda/${functionName}") {
                                    lambdaDeploy environment: stageEnv,
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "lambda-${sanitizedFunctionName}",
                                        functionName: "${stageEnv}-${sanitizedFunctionName}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: deploymentTargets[stageEnv].accountId,
                                        awsDeploymentRoleName: deploymentTargets[stageEnv].deploymentRole

                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Publish Software Catalog Definitions') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        // Apply name standardization
                        def sanitizedFunctionName = functionName.replaceAll('aws_', '').replaceAll('_', '-')
                        return [
                            (functionName): {
                                echo "Publishing Software Catalog definition for ${functionName}"
                                datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        // stage('E2E Tests') {
        //     when {
        //         branch 'master'
        //     }
        //     steps {
        //         build job: 'break-glass-e2e-cucumber-cypress-prod-tests'
        //     }
        // }
    }

    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 getFunctionsToBuild() {
    if (this.@functionsToBuild != null) {
        return this.@functionsToBuild
    }

    def dockerfiles = findFiles(glob: 'lambda/*/Dockerfile')
    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

    if (lambdaFunctionName == '*') {
        // https://github.com/theorchard/jenkins-global-libraries/blob/master/vars/getModifiedFunctions.groovy
        this.@functionsToBuild = \
            dockerfiles.collect{ it.path.replaceAll('/Dockerfile$', '') }.\
            collect{ it.tokenize('/').last() }
    }
    else if (lambdaFunctionName) {
        this.@functionsToBuild = [lambdaFunctionName]
    } else {
        this.@functionsToBuild = getModifiedFunctions branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            lambdaDirectories: dockerfiles
    }

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

    return this.@functionsToBuild
}
