@Library('nf-jenkins-shared-libraries')_  

def slavepool = "slave01 slave02 master"
def SLEEP = 5
def repo = "billing"
MVN_HOME='mvn_local_repository'


//Choose available slave to run job

pipeline {
    agent any
    environment {
        DOCKER_HUB = credentials('dockerhub')
        SONAR_CLOUD = credentials('sonar')
        X_RAY = credentials("x_ray_user")
        BITBUCKET_AUTH = credentials('bitbucket_auth')
        SRCCLR_API_TOKEN = credentials('SRCCLR_API_TOKEN')
    }
    tools {
        maven 'apache-maven-3.6.0'
    }
    stages {

         stage('Build') {
            steps {
                script {
                    echo "Running on ${NODE_NAME}"
                    bitbucketStatus repo: "${repo}", BRANCH_NAME: "${BRANCH_NAME}", GIT_COMMIT: "${GIT_COMMIT}", status: "INPROGRESS"
                    sh "mkdir -p ${MVN_HOME}/${BUILD_NUMBER}"
                    dir("${MVN_HOME}/${BUILD_NUMBER}") {
                        sh "for dir in \$(ls \$HOME/.m2/repository/ | grep -v 'io'); do ln -s \$HOME/.m2/repository/\$dir \$dir; done"
                    }
                    sh "export JAVA_HOME=/usr/lib/jvm/java-11-amazon-corretto.x86_64/; mvn -Dmaven.repo.local=${MVN_HOME}/${BUILD_NUMBER} -T 8 clean install dependency-check:check"
                }
            }
        }

        stage('Sonar') {
            steps {
                script {
                    sh "export JAVA_HOME=/usr/lib/jvm/java-11-amazon-corretto.x86_64/; mvn verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dmaven.repo.local=${MVN_HOME}/${BUILD_NUMBER} -Dsonar.host.url=https://sonarcloud.io "+
                       "-Dsonar.organization=netfoundry -Dsonar.projectKey=io.netfoundry:billing "+ 
                       "-Dsonar.branch.name=${BRANCH_NAME} -Dsonar.login=${SONAR_CLOUD_PSW} "+
                       "-Dsonar.java.pmd.reportPaths=target/dependency-check-report-pmd.xml "
                }
            }
        }

        stage('Docker') {
            when { expression { BRANCH_NAME == "develop" || BRANCH_NAME ==~ /(release.*)/ || BRANCH_NAME ==~ /(hotfix.*)/ }}
            steps {
                script {
                    buildDocker REPO: "${repo}", GIT_COMMIT: "${GIT_COMMIT}", BUILD_NUMBER: "${BUILD_NUMBER}", BRANCH_NAME: "${BRANCH_NAME}"
                    if(BRANCH_NAME == "develop") {
                        veracodeContainerScan REPO: "${repo}"
                    }
                    try {
                        sh "docker rmi netfoundry/${repo}:${GIT_COMMIT}"
                        sh "docker rmi netfoundry/${repo}:sandbox"
                        sh "docker rmi netfoundry/${repo}:latest"
                    } catch(err) {
                        echo "Docker images cleanup not done: ${err}"
                    }
                }
            }
        }


        stage('Terraform'){
            when { expression { BRANCH_NAME == "develop"  }}
            steps {
                script { 
                    terraform directory: "terraform", environment: "sandbox"
                }
            }
        }

        stage('Deployment') {
            when { expression { BRANCH_NAME == "develop" }}
            steps {
                script {
                    withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: "aws_sandbox", variable: 'AWS_ACCESS_KEY_ID']]) {
                        sh "ecs deploy --region us-east-1 --timeout 600 ecs-cluster-nfn-internal-env-private ecs-${repo}-service"
                    }
                }
            }
        }

        stage('Promote to Staging') {
            when { expression { BRANCH_NAME == "develop" }}
            steps {
                script {
                    build_job = build job: 'Continuous Deployment - Promotions', parameters: [
                        [$class: 'StringParameterValue', name: 'commit_hash', value: "${GIT_COMMIT}"],
                        [$class: 'StringParameterValue', name: 'REPO', value: "${repo}"],
                        [$class: 'StringParameterValue', name: 'environment', value: "staging"],
                        [$class: 'StringParameterValue', name: 'action', value: 'promote'],
                        [$class: 'BooleanParameterValue', name: 'run_tests', value: false],
                        [$class: 'BooleanParameterValue', name: 'database_backup', value: false],
                        [$class: 'BooleanParameterValue', name: 'slack_notify', value: true],
                        [$class: 'BooleanParameterValue', name: 'run_terraform', value: true],
                        [$class: 'BooleanParameterValue', name: 'run_ecs_deploy', value: true],
                        [$class: 'BooleanParameterValue', name: 'run_post_deploy_tests', value: true],
                    ], propagate: false, wait: false
                }
            }
        }
    }
    post {
        always {
            sh "rm -rf ${MVN_HOME}/${BUILD_NUMBER}"
        }
        aborted {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, status: "STOPPED"
        }
        failure {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, status: "FAILED"
            script {
                if( "${BRANCH_NAME}" == "develop" ){
                    mattermostFailureNotification repo: "${repo}", commit: GIT_COMMIT, build_url: RUN_DISPLAY_URL, channel: "cd-mop-staging"
                }
            }
        }
        success {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, status: "SUCCESSFUL"
        }
    }
}

