String GITHUB_REPOSITORY = 'ows-asset-transcoder'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#podcast-team'
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'

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        booleanParam(name: 'RUN_E2E_TESTS_ONLY', defaultValue: false, description: 'Check this to <b>just</b> run the E2E tests. No other stages will be run, regardless of other parameter values.')
        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.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                complianceChecks()
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                sh 'make ci_unit_lint'
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    cobertura coberturaReportFile: 'coverage.xml', failNoReports: true, failUnhealthy: true, failUnstable: true, zoomCoverageChart: true, onlyStable: false
                }
            }
        }
        stage('Static Application Security Tests') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT, dockerBuildTarget: 'deploy'
            }
        }
        stage('Scan Docker Image') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT, failBuild: false
            }
        }
        stage('Deploy to QA') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }
        stage('Integration Tests') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                sh 'make ci_test_integration'
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                MAKE_TARGET = "cypress_run_${GITHUB_REPOSITORY.replaceAll('-', '_')}"
                UTILS_GRASS_VERSION = '0.6.1'
                QA_GRASS_HOST = 'https://api-dev.theorchard.io/auth/session'
                QA_DB_DATABASE='art_relations'
                QA_DB_HOST='qadb01.qaorch.com'
            }
            steps {
                dir('frontend-podcast') {
                    checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '577cbc72-7d9e-4eba-924c-ecbbe6de9805', url: "git@github.com:theorchard/frontend-podcast.git"]]])

                    script {
                        withCredentials([
                            aws(credentialsId: 'cucumber-tests'),
                            string(credentialsId: 'packagecloud_repo_token', variable: 'PACKAGECLOUD_TOKEN'),
                            string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN'),
                            string(credentialsId: 'frontend-podcast-password', variable: 'CYPRESS_PASSWORD'),
                            usernamePassword(credentialsId: 'qa-automation-ardb-credentials', usernameVariable: 'QA_DB_USER', passwordVariable: 'QA_DB_PASS')
                        ]) {
                            nodejs(nodeJSInstallationName: 'nodejs 16.19.1') {
                                ansiColor('xterm') {
                                    try {
                                        sh '''
                                        #!/bin/bash
                                        # Remove report from previous run
                                        find . -type f -name allure-report.zip -delete
                                        
                                        # sets up grass token - using @USER_ID@

                                        rm -fR env

                                        # create the environment
                                        python3 -m venv env
                                        . env/bin/activate

                                        pip install --upgrade pip

                                        pip install -i https://pypi.theorchard.io/pypi/ qa-utils-grass==$UTILS_GRASS_VERSION

                                        # Set the GRASS_TOKEN environment variable using command substitution
                                        GRASS_TOKEN=$(python -c "from auth.auth import GrassAuth, UserType; workstation_token = GrassAuth(UserType.OA, 9).grass_token; print(workstation_token)")

                                        # Set the ORCHARD_IDENTITY_UUID environment variable
                                        ORCHARD_IDENTITY_UUID="oa:9"

                                        # Export the variables to make them available in the current shell
                                        export GRASS_TOKEN ORCHARD_IDENTITY_UUID

                                        node --version
                                        yarn --version
                                        scripts/setup.sh

                                        #getting variables from AWS
                                        ./scripts/checkEnv.sh

                                        yarn install

                                        export CYPRESS_BASE_URL=https://podcast.qaorch.com/
                                        yarn test:integration:assets
                                        '''
                                    } finally {
                                        allure(
                                            report: 'allure-report',
                                            results: [
                                                [path: 'allure-results']
                                            ],
                                            config: [
                                                jdk              : 'InheritFromJob',
                                                reportBuildPolicy: 'ALWAYS'
                                            ]
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
            post {
                regression {
                    slackNotify(channel: SLACK_NOTIFICATIONS_CHANNEL)
                }
                fixed {
                    slackNotify(channel: SLACK_NOTIFICATIONS_CHANNEL)
                }
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
            }
        }
    }

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