String GITHUB_REPOSITORY = 'monday-com-orca-backend'
String ECR_ACCOUNT_ID = '086679231553'

List<String> AWS_REGIONS = ['us-east-1']
String QA_ACCOUNT_ID = '814622134907'
String QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String PROD_ACCOUNT_ID = '009424872958'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'
String BUILD_ROLE = 'qa-monday-com-orca-backend-integration-test-role'
String SLACK_NOTIFICATIONS_CHANNEL = null

pipeline {
    agent any

    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, 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 {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                withEcr{
                    sh 'make ci_unit_lint'
                }
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'build/pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'build/coverage.xml']], enabledForFailure: true, failOnError: true, sourceDirectories: [[path: "monday_com_orca_backend"]])
                }
                cleanup {
                    sh 'make ci_unit_lint_clean'
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    dockerBuildTarget: 'deploy'
            }
        }
        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: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }
        stage('Scan Docker Image') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                slackNotificationChannel: (env.BRANCH_NAME == 'master' ? SLACK_NOTIFICATIONS_CHANNEL : null)
            }
        }
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withSecrets(awsAccountId: '814622134907', awsRole: BUILD_ROLE, secrets: [
                    [id: 'qa/monday-com-orca-backend/MONDAY_APP_SNOWFLAKE_PRIVATE_KEY', environmentVariable: 'SNOWFLAKE_PRIVATE_KEY'],
                    [id: 'qa/monday-com-orca-backend/MONDAY_APP_CLIENT_SECRET', environmentVariable: 'MONDAY_APP_CLIENT_SECRET'],
                ]) {
                    sh 'make ci_test_integration'
                }
            }
            post {
                cleanup {
                    sh 'make ci_test_integration_clean'
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                // Use the following line if there's a tag in cucumber-cypress-tests. For example: @ows_account
                // TAGS = "@${GITHUB_REPOSITORY.replaceAll('-', '_')}"
                // Otherwise, keep the following which runs smoke tests on qa environment
                TAGS = "@qa_smoke"
            }
            steps {
                // e2eTests tags: env.TAGS
                echo "not implemented yet"
            }
            post {
                regression {
                    slackNotify channel: '#cypress-test-e2e-results'
                }
                fixed {
                    slackNotify channel: '#cypress-test-e2e-results'
                }
            }
        }
        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: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
