String GITHUB_REPOSITORY = 'lambda-nr-ownership-ingest-reporter'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#knr-alerts'
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'

def modifiedFunctionList = []

pipeline {
    agent any

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

    parameters {
        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 or Git revision.')
    }

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

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Find Modified Functions') {
            steps {
                script {
                    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

                    if (lambdaFunctionName) {
                        modifiedFunctionList = [lambdaFunctionName]
                    } else {
                        def lambdaDirectories = findFiles(glob: 'lambda/**/Dockerfile')
                        modifiedFunctionList = getModifiedFunctions(lambdaDirectories)
                    }
                }
            }
        }

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

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

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

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

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Building for ${functionName}"
                                dockerToEcr awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: "lambda-${functionName}",
                                    imageTag: env.GIT_COMMIT,
                                    dockerBuildContext: "lambda/${functionName}",
                                    dockerBuildFile: "lambda/${functionName}/Dockerfile"
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to QA for ${functionName}"
                                dir("lambda/${functionName}") {
                                    lambdaDeploy environment: 'qa',
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "lambda-${functionName}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                        awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Scanning Docker Images for ${functionName}"
                                dir("lambda/${functionName}") {
                                    dockerScan awsRegion: AWS_REGIONS[0],
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: "lambda-${functionName}",
                                        imageTag: env.GIT_COMMIT
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to PROD for ${functionName}"
                                dir("lambda/${functionName}") {
                                    lambdaDeploy environment: 'prod',
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "lambda-${functionName}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                        awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                                }
                            }
                        ]
                    })
                }
            }
        }
    }

    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 getModifiedFunctions(lambdaDirectories) {
    def modifiedFunctions = []

    if (env.BRANCH_NAME == 'master' && !env.GIT_PREVIOUS_SUCCESSFUL_COMMIT) {
        for (dockerfile in lambdaDirectories) {
            def functionDir = dockerfile.path.replaceAll('/Dockerfile$', '')
            def functionName = functionDir.tokenize('/').last()
            modifiedFunctions.add(functionName)
        }
    } else {
        def commonAncestor = env.BRANCH_NAME == 'master' && env.GIT_PREVIOUS_SUCCESSFUL_COMMIT ?
            env.GIT_PREVIOUS_SUCCESSFUL_COMMIT :
            sh(script: "git merge-base ${env.GIT_COMMIT} origin/master", returnStdout: true).trim()

        for (dockerfile in lambdaDirectories) {
            def functionDir = dockerfile.path.replaceAll('/Dockerfile$', '')
            def gitDiff = sh(script: "git diff --name-only ${commonAncestor}..${env.GIT_COMMIT} ${functionDir}", returnStdout: true).trim()

            if (!gitDiff.empty) {
                def functionName = functionDir.tokenize('/').last()
                modifiedFunctions.add(functionName)
            }
        }
    }

    echo "Detected modifications in the following functions: ${modifiedFunctions}"
    return modifiedFunctions
}
