String GITHUB_REPOSITORY = 'lambda-audience'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#fansifter-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'

// Fansifter specific
String FANSIFTER_QA_ACCOUNT_ID = '285943604611'
String FANSIFTER_PROD_ACCOUNT_ID = '737325105821'
String FANSIFTER_QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String FANSIFTER_PROD_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'
List<String> FANSIFTER_FUNCTIONS = [
    'refresh-m2m-token',
    "sendgrid-webhooks",
    "sendgrid-webhooks-custom-handlers",
    "sendgrid-webhooks-inbound",
    'songwhip-event-processor',
    'songwhip-fan-consent-handler',
    "test-audiences-cleanup",
    "twilio-send-messages",
    "twilio-webhooks-inbound",
    "twilio-webhooks-outbound",
    "validate-email-domains",
    "text-campaigns-dispatcher",
    "text-campaigns-sender",
    "email-campaigns-dispatcher",
    "email-campaigns-sender",
    "automated-emails-sender",
    "briteverify-email-validator",
]
List<String> FANSIFTER_E2E_FUNCTIONS = [
    'export-audience-file',
    'share-audience',
]

@groovy.transform.Field
List<String> functionsToBuild = null
List<String> VULNERABILITIES_TO_IGNORE = [
    "CVE-2023-45853",
    "GHSA-87m9-rv8p-rgmg"
]

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')
        choice(name: 'SKIP_E2E_TESTS', choices: ['No', 'Yes'], description: 'Whether or not to skip e2e tests step')
        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 {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Compliance Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    complianceChecks()
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            steps {
                script {
                    def region = AWS_REGIONS[0]
                    sh """
                        aws ecr get-login-password --region ${region} | \
                        docker login --username AWS --password-stdin ${ECR_ACCOUNT_ID}.dkr.ecr.${region}.amazonaws.com
                    """
                    parallel(getFunctionsToBuild().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(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('Validate Software Catalog Definitions') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Validating Software Catalog definition for ${functionName}"
                                datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

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

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to QA for ${functionName}"
                                dir("lambda/${functionName}") {
                                    String accountId = FANSIFTER_FUNCTIONS.contains(functionName) ? FANSIFTER_QA_ACCOUNT_ID : QA_ACCOUNT_ID
                                    String deploymentRole = FANSIFTER_FUNCTIONS.contains(functionName) ? FANSIFTER_QA_DEPLOYMENT_ROLE : QA_DEPLOYMENT_ROLE
                                    lambdaDeploy environment: 'qa',
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: accountId,
                                        awsDeploymentRoleName: deploymentRole
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Scanning Docker Images for ${functionName}"
                                dir("lambda/${functionName}") {
                                    dockerScan awsRegion: AWS_REGIONS[0],
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: "${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                                        imageTag: env.GIT_COMMIT,
                                        vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE,
                                        failBuild: false
                                }
                            }
                        ]
                    })
                }
            }
        }
        stage('E2E tests') {
            when {
                allOf {
                    branch 'master'
                    expression { params.SKIP_E2E_TESTS == 'No' }
                    expression {getFunctionsToBuild().any { FANSIFTER_E2E_FUNCTIONS.contains(it) } }
                }
            }
            steps {
                playwrightTests tags: getFunctionsToBuild().findAll { FANSIFTER_E2E_FUNCTIONS.contains(it) }.collect { '@' + it.replaceAll('_', '-') + '-lambda' }.join(' or ')
            }
        }

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to PROD for ${functionName}"
                                dir("lambda/${functionName}") {
                                    String accountId = FANSIFTER_FUNCTIONS.contains(functionName) ? FANSIFTER_PROD_ACCOUNT_ID : PROD_ACCOUNT_ID
                                    String deploymentRole = FANSIFTER_FUNCTIONS.contains(functionName) ? FANSIFTER_PROD_DEPLOYMENT_ROLE : PROD_DEPLOYMENT_ROLE
                                    lambdaDeploy environment: 'prod',
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: "${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: accountId,
                                        awsDeploymentRoleName: deploymentRole
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Publish Software Catalog Definition') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Updating Software Catalog definition for ${functionName}"
                                datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }
    }



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

    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

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

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

    return this.@functionsToBuild
}
