String GITHUB_REPOSITORY = 'lambda-physical-delivery'
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 = [
    'order-finalizer': [
    ],
    'product-hydrator': [
    ],
]

pipeline {
    agent none

    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_NAMES',
            defaultValue: '',
            description: 'Comma-separated list of Lambda function directory names 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).'
        )
        booleanParam(
            name: 'VERIFY_BUILD',
            defaultValue: false,
            description: 'Force build and test step to verify health.'
        )
    }

    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('Sonar Scan and Analysis') {
            agent any
            when {
                branch 'master'
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Sonar scan for ${functionName}"
                    sonarScan(
                        project: "lambda-phy-delivery-${functionName}",
                        projectBaseDir: "lambda/${functionName}",
                        language: 'ts'
                    )
                }
            }
        }
        stage('Build Test and Scan') {
            when {
                expression { isPullRequest() || params.VERIFY_BUILD }
            }
            parallel {
                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') {
                    environment {
                        GITHUB_TOKEN = credentials('github_packages_token')
                    }
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Running Unit Tests and Style Checks for ${functionName}"
                            dir("lambda/${functionName}") {
                                withEcr {
                                    sh "docker compose run --rm --build lint-and-test"
                                }
                            }
                        }
                    }
                    post {
                        cleanup {
                            withModifiedFunctions(checkout: true) { functionName ->
                                echo "Cleaning up for ${functionName}"
                                dir("lambda/${functionName}") {
                                    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 imageName = "lambda-phy-delivery-${functionName}"
                                echo "Building for ${functionName}"
                                withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]) {
                                    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",
                                        dockerBuildSecrets: [[id: 'tokens', env: 'GITHUB_TOKEN']],
                                    )
                                }
                                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 imageName = "lambda-phy-delivery-${functionName}"
                        def commit = getCommitHash(functionName)
                        def prNumber = githubGetCommitPrs(
                            repo: GITHUB_REPOSITORY,
                            commitSha: commit
                        )[0].number
                        retagEcrImage(
                            awsRegions: AWS_REGIONS,
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: 'PR-' + prNumber,
                            newTag: commit
                        )
                        dockerScan(
                            awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: commit,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE[functionName]
                        )
                    }
                }
            }
        }
        stage('Deploy to QA') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                script {
                    withModifiedFunctions(checkout: true) { functionName ->
                        echo "Deploying to QA for ${functionName}"
                        def commitHash = getCommitHash(functionName)
                        dir("lambda/${functionName}") {
                            lambdaDeploy(
                                environment: 'qa',
                                awsRegions: AWS_REGIONS,
                                imageTag: commitHash,
                                imageName: "lambda-phy-delivery-${functionName}",
                                ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                            )
                        }
                    }
                }
            }
        }
        stage('Deploy to PROD') {
            when {
                expression { !isPullRequest() && params.DEPLOY_TO_PROD }
            }
            steps {
                script {
                    withModifiedFunctions(checkout: true) { functionName ->
                        echo "Deploying to PROD for ${functionName}"
                        def commitHash = getCommitHash(functionName)
                        dir("lambda/${functionName}") {
                            lambdaDeploy(
                                environment: 'prod',
                                awsRegions: AWS_REGIONS,
                                imageTag: commitHash,
                                imageName: "lambda-phy-delivery-${functionName}",
                                ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                            )
                        }
                        echo "Updating 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
    )
}
