String GITHUB_REPOSITORY = 'offboarding-automation'
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 = [
    'shared': [
        'accountId': '086679231553',
        'deploymentRole': 'shared-jenkins-pipeline-deploy-role'
    ]
]

def functionDeploymentMap = [
    'auth0_cli': [
        'prod': ['shared'],
    ],
    'github_cli': [
        'prod': ['shared'],
    ],
    'jira_cli': [
        'prod': ['shared']
    ],
    'dynamo_cli': [
        'prod': ['shared']
    ],
]

@groovy.transform.Field
def monorepoUtilsInstance = null

pipeline {
    agent none

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

    parameters {
        string(name: 'DEPLOY_TO_PROD', defaultValue: 'false', description: 'Set to true to enable deployment to production environment')
        string(name: 'LAMBDA_FUNCTION_NAMES', defaultValue: '', description: 'Comma-separated list of names of 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.*')
    }

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

        stage('Compliance Checks') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Compliance Checks for ${functionName}"
                    dir("lambda/${functionName}") {
                        complianceChecks()
                    }
                }
            }
        }

        stage('Validate Software Catalog Definition') {
            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}") {
                            sh 'make docker_test'
                        }
                    }
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Static App Security Tests for ${functionName}"
                    sastTests(projectDir: "lambda/${functionName}")
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            agent any
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py', exclusions: 'lambda/**/tests/**'
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Building for ${functionName}"
                    dockerToEcr awsRegions: AWS_REGIONS,
                        ecrAccountId: ECR_ACCOUNT_ID,
                        imageName: "lambda-${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                        imageTag: env.GIT_COMMIT,
                        dockerBuildContext: "lambda/${functionName}",
                        dockerBuildFile: "lambda/${functionName}/Dockerfile",
                        additionalContexts: [shared: 'lambda/shared']
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                withModifiedFunctions { functionName ->
                    echo "Scanning Docker Images for ${functionName}"
                    dir("lambda/${functionName}") {
                        dockerScan awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: "lambda-${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                            imageTag: env.GIT_COMMIT,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }

        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running integration tests for ${functionName}"
                    withEcr {
                        dir("lambda/${functionName}") {
                            sh 'make docker_test_integration'
                        }
                    }
                }
            }
        }

         stage('Deploy to PROD') {
             when {
                 allOf {
                     branch 'master'
                     expression { params.DEPLOY_TO_PROD }
                 }
             }
             steps {
                 withModifiedFunctions(checkout: true) { functionName ->
                     echo "Deploying to PROD for ${functionName}"
                     dir("lambda/${functionName}") {
                         script {
                             functionDeploymentMap[functionName]['prod'].each { account ->
                                 lambdaDeploy environment: 'shared',
                                     awsRegions: AWS_REGIONS,
                                     imageTag: env.GIT_COMMIT,
                                     imageName: "lambda-${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                                     ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                     awsDeploymentTargetAccountId: deploymentTargets[account].accountId,
                                     awsDeploymentRoleName: deploymentTargets[account].deploymentRole
                             }
                         }
                     }
                     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
                }
            }
        }
    }
}

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

def getMonorepoUtils() {
    if (monorepoUtilsInstance == null) {
        monorepoUtilsInstance = library("jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}").com.sonymusic.MonorepoUtils.getInstance(
            steps: this,
            projectBasePath: 'lambda',
            excludedProjects: ['shared'],
            projectsToBuild: params.LAMBDA_FUNCTION_NAMES ? params.LAMBDA_FUNCTION_NAMES.split(',') : null
        )
    }
    return monorepoUtilsInstance
}
