def APP_NAME = 'frontend-pricing'
def SLACK_NOTIFICATIONS_CHANNEL = '#content-creation-mgmt-alerts'
def DEFAULT_AWS_REGION = 'us-east-1'

def QA_CDN_URL = 'https://qa-cdn.theorchard.io'
def PROD_CDN_URL = 'https://cdn.theorchard.io'

pipeline {
    agent {
        label 'aws'
    }

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

    parameters {
        choice(name: 'DEPLOY_TO_PROD', choices: ['Yes', 'No'], description: 'Whether or not to deploy to prod.')
        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.*|.*deploy pri.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'deploy pri'
                }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    yarnRun([
                        scriptNames: ['test'],
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}"
                        ]
                    ])
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${APP_NAME}"
                    sonarScan project: APP_NAME, language: 'js'
                }
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                // Build
                withCredentials([string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN')]) {
                    yarnRun ([
                        scriptNames: ['build'],
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            ENV: 'qa',
                            MINIFY: params.MINIFY,
                            CDN_URL: QA_CDN_URL,
                            DEPLOY_TIMESTAMP: env.GIT_COMMIT,
                            TIMESTAMP: env.GIT_COMMIT,
                            APPLICATION_NAME: 'manage-pricing'
                        ]
                    ])
                }

                // Publish
                withAWS(region: DEFAULT_AWS_REGION, credentials: 'cdn-deploy') {
                    step([$class: 'hudson.plugins.s3.S3BucketPublisher',
                            entries: [
                                [bucket: "qa-orcd-cdn/${APP_NAME}/${env.GIT_COMMIT}",
                                excludedFile: 'build/manifest.json',
                                sourceFile: 'build/',
                                selectedRegion: DEFAULT_AWS_REGION,
                                flatten: true,
                                noUploadOnFailure: true],
                                [bucket: "qa-orcd-cdn/${APP_NAME}",
                                sourceFile: 'build/*.*',
                                selectedRegion: DEFAULT_AWS_REGION,
                                flatten: true,
                                noUploadOnFailure: true]
                            ]
                    ])
                }
            }
        }
        stage('Invalidate QA CDN') {
            when {
                branch 'master'
            }
            steps {
                cdnInvalidate(
                    env: 'qa',
                    appName: APP_NAME
                )
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = '@frontend_pricing'
            }
            steps {
                playwrightTests tags: env.TAGS
            }
        }
        stage('Publish Software Catalog') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
        stage('Deploy to Prod') {
           when {
               allOf {
                   branch 'master'
                   expression { params.DEPLOY_TO_PROD == 'Yes' }
               }
           }
           steps {
               // Build
               withCredentials([string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN')]) {
                   yarnRun ([
                       scriptNames: ['build'],
                       envVars: [
                           PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                           ENV: 'prod',
                           MINIFY: params.MINIFY,
                           CDN_URL: PROD_CDN_URL,
                           DEPLOY_TIMESTAMP: env.GIT_COMMIT,
                           TIMESTAMP: env.GIT_COMMIT,
                           APPLICATION_NAME: 'manage-pricing'
                       ]
                   ])
               }

               // Publish
               withAWS(region: DEFAULT_AWS_REGION, credentials: 'cdn-deploy') {
                   step([$class: 'hudson.plugins.s3.S3BucketPublisher',
                           entries: [
                               [bucket: "prod-orcd-cdn/${APP_NAME}/${env.GIT_COMMIT}",
                               excludedFile: 'build/manifest.json',
                               sourceFile: 'build/',
                               selectedRegion: DEFAULT_AWS_REGION,
                               flatten: true,
                               noUploadOnFailure: true],
                               [bucket: "prod-orcd-cdn/${APP_NAME}",
                               sourceFile: 'build/*.*',
                               selectedRegion: DEFAULT_AWS_REGION,
                               flatten: true,
                              noUploadOnFailure: true]
                           ]
                   ])
               }
           }
        }
        stage('Invalidate Prod CDN') {
           when {
               allOf {
                   branch 'master'
                   expression { params.DEPLOY_TO_PROD == 'Yes' }
               }
           }
           steps {
               cdnInvalidate(
                   env: 'prod',
                   appName: APP_NAME
               )
           }
        }
    }

    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()
        }
    }
}
