String GITHUB_REPOSITORY = 'daemon-notifications-delivery'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#notifications'
String ACCOUNT_ID = '437795906767'
String DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String INTEGRATION_TEST_ROLE = 'qa-daemon-notifications-delivery-integration-test-role'
String SESSION_NAME = 'qa-daemon-notifications-delivery-integration-test'
String POEDITOR_PROJECT_ID = '202965'

def integrationTestsDelay = 30 // Time to wait in seconds after deployment to QA
def integrationTestsMaxRetries = 3 // Number of retries for integration tests


pipeline {
    agent {
        label 'aws'
    }

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, 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.*|.*run integration tests.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'run integration tests'
                }
            }
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('ECR login') {
            steps {
                sh """
                    aws ecr get-login-password --region ${AWS_REGIONS[0]} | docker login --username AWS --password-stdin ${ECR_ACCOUNT_ID}.dkr.ecr.${AWS_REGIONS[0]}.amazonaws.com
                """
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'run integration tests'
                }
            }
            agent {
                dockerfile {
                    additionalBuildArgs "--target tests"
                    args "-v ${PWD}:/var/app"
                    reuseNode true
                }
            }
            steps {
                sh 'make VENV=/var/venv ci_check'
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'coverage.xml']], enabledForFailure: true, failOnError: true, sourceDirectories: [[path: "notifications_delivery"]])
                }
            }
        }
        stage('Static Application Security Tests') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'run integration tests'
                }
            }
            steps {
                sastTests()
            }
        }
//         stage('Sonar Scan and Analysis') {
//             when {
//                 branch 'master'
//             }
//             steps {
//                 sonarScan project: GITHUB_REPOSITORY, language: 'py'
//             }
//         }
        stage('Create a Release') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([string(credentialsId: 'poeditor-api-token', variable: 'POEDITOR_API_TOKEN')]) {
                    dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                        imageTag: env.GIT_COMMIT, dockerBuildTarget: 'main',
                        dockerBuildArgs: [POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID],
                        dockerBuildSecrets: [[id: 'poeditor_api_token', env: 'POEDITOR_API_TOKEN']]
                }
            }
        }
        stage('Scan Docker Image') {
            when {
                branch 'master'
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                 imageTag: env.GIT_COMMIT, failBuild: false
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                    serviceName: GITHUB_REPOSITORY, ecrRegistryAccountId: ECR_ACCOUNT_ID,
                    awsDeploymentTargetAccountId: ACCOUNT_ID, awsDeploymentRoleName: DEPLOYMENT_ROLE
            }
        }
        stage('Integration Tests') {
            when {
                anyOf {
                    branch 'master'
                    expression {
                        return env.CHANGE_ID && env.GITHUB_COMMENT == 'run integration tests'
                    }
                }
            }
            agent {
                dockerfile {
                    additionalBuildArgs "--target tests"
                    args "-v ${PWD}:/var/app"
                    reuseNode true
                }
            }
            steps {
                retry(integrationTestsMaxRetries) {
                    withAWS(role: INTEGRATION_TEST_ROLE, roleAccount: ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh 'make VENV=/var/venv test_integration'
                    }
                }
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                    serviceName: GITHUB_REPOSITORY, ecrRegistryAccountId: ECR_ACCOUNT_ID,
                    awsDeploymentTargetAccountId: ACCOUNT_ID, awsDeploymentRoleName: DEPLOYMENT_ROLE
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
    }
}
