String GITHUB_REPOSITORY = 'lambda-releases.theorchard.com'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#distro-build-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'

Map<String, List<String>> VULNERABILITIES_TO_IGNORE = [
    'new_release_json_blaster': []
]

pipeline {
    agent none

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

    parameters {
        booleanParam(
            name: 'DEPLOY_TO_PROD',
            defaultValue: true,
            description: 'Whether or not to deploy to prod.'
        )
        booleanParam(
            name: 'VERIFY_BUILD',
            defaultValue: false,
            description: 'Force build and test step to verify health.'
        )
        string(
            name: 'LAMBDA_FUNCTION_NAMES',
            defaultValue: '',
            description: 'Comma-separated names of the Lambda functions 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.*')
        parameterizedCron(env.BRANCH_NAME == 'master' ? '@weekly %DEPLOY_TO_PROD=false;VERIFY_BUILD=true;LAMBDA_FUNCTION_NAMES=*' : '')
    }

    stages {
        stage('Load Shared Libraries') {
            agent any
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Build Test and Scan') {
            when {
                expression { isPullRequest() || params.VERIFY_BUILD }
            }
            parallel {
                stage('Sonar Scan and Analysis') {
                    agent any
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Running Sonar scan for ${functionName}"
                            sonarScan(
                                project: "lambda-releases-orcd-${functionName.replaceAll('_', '-')}",
                                language: 'py',
                                projectBaseDir: "lambda/${functionName}",
                                qualityGateTimeout: 300
                            )
                        }
                    }
                }
                stage('Compliance Checks') {
                    agent any
                    steps {
                        complianceChecks()
                    }
                }
                stage('Validate Software Catalog Definitions') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Validating Software Catalog definition for ${functionName}"
                            datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                        }
                    }
                }
                stage('Unit Tests and Style Checks') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Running Unit Tests and Style Checks for ${functionName}"
                            withEcr {
                                dir("lambda/${functionName}") {
                                    script {
                                        try {
                                            sh "docker compose run --rm --build lint-and-test"
                                        }
                                        finally {
                                            sh "docker compose down -v"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Running Static App Security Tests for ${functionName}"
                            sastTests(projectDir: "lambda/${functionName}")
                        }
                    }
                }
                stage('Create and Docker Scan a Release') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            script {
                                def sanitizedFunctionName = sanitizeFunctionName(functionName)
                                def imageName = "lambda-releases-orcd-${sanitizedFunctionName}"
                                echo "Building for ${functionName}"
                                dockerToEcr(
                                    awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: imageName,
                                    imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                                    dockerBuildContext: "lambda/${functionName}",
                                    dockerBuildFile: "lambda/${functionName}/Dockerfile",
                                    dockerBuildTarget: "deploy"
                                )
                                dockerScan(
                                    awsRegion: AWS_REGIONS[0],
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: imageName,
                                    imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                                    vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE[functionName]
                                )
                            }
                        }
                    }
                }
            }
        }
        stage('Retag and Docker Scan a Release') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def imageName = "lambda-releases-orcd-${sanitizedFunctionName}"
                        def commitHash = getCommitHash(functionName)
                        def prNumber = githubGetCommitPrs(
                            repo: GITHUB_REPOSITORY,
                            commitSha: commitHash
                        )[0].number
                        retagEcrImage(
                            awsRegions: AWS_REGIONS,
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: 'PR-' + prNumber,
                            newTag: commitHash
                        )
                        dockerScan(
                            awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: commitHash,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE[functionName]
                        )
                    }
                }
            }
        }
        stage('Deploy to QA') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def commitHash = getCommitHash(functionName)
                        echo "Deploying to QA for ${functionName}"
                        dir("lambda/${functionName}") {
                            lambdaDeploy(
                                environment: 'qa',
                                awsRegions: AWS_REGIONS,
                                imageTag: commitHash,
                                imageName: "lambda-releases-orcd-${sanitizedFunctionName}",
                                ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                            )
                        }
                    }
                }
            }
        }
        stage('Integration Tests') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Integration tests for ${functionName}"
                    withEcr {
                        dir("lambda/${functionName}") {
                            script {
                                try {
                                    sh 'docker compose run --rm --build test-integration'
                                }
                                finally {
                                    sh 'docker compose down -v'
                                }
                            }
                        }
                    }
                }
            }
        }
        stage('Deploy to PROD') {
            when {
                expression { params.DEPLOY_TO_PROD && !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def commitHash = getCommitHash(functionName)
                        echo "Deploying to PROD for ${functionName}"
                        dir("lambda/${functionName}") {
                            lambdaDeploy(
                                environment: 'prod',
                                awsRegions: AWS_REGIONS,
                                imageTag: commitHash,
                                imageName: "lambda-releases-orcd-${sanitizedFunctionName}",
                                ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                            )
                        }
                        echo "Publishing Software Catalog definition for ${functionName}"
                        datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                    }
                }
            }
        }
    }

    post {
        regression {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
    }
}

def isPullRequest() {
    return env.BRANCH_NAME != 'master'
}

def getCommitHash(String functionName) {
    return sh(
        script: "git log -1 --pretty=format:'%H' -- lambda/${functionName}",
        returnStdout: true
    ).trim()
}

def sanitizeFunctionName(String functionName) {
    return functionName.replaceAll('_', '-')
}

def withModifiedFunctions(Map args = [:], Closure steps) {
    getMonorepoUtils().withModifiedProjects(args, steps)
}

def getMonorepoUtils() {
    return library("jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}").com.sonymusic.MonorepoUtils.getInstance(
        steps: this,
        projectBasePath: 'lambda',
        projectsToBuild: params.LAMBDA_FUNCTION_NAMES ? params.LAMBDA_FUNCTION_NAMES.split(',') as Set : null
    )
}
