@Library('nf-jenkins-shared-libraries')_
import org.apache.commons.codec.digest.DigestUtils;

def repo = "notification"

MVN_HOME='mvn_local_repository'
BRANCH_NAME="develop"

STAGING_IMAGE = ""

dep_environment = "sandbox"
build_status = "SUCCESS"

currentDeployedCommit = ""
smoketest_url = ""
artifact_link = ""
failure_msg = ""
commit_hash = ""
stage_name = ""
child_url = ""
link_url = ""
dlink = ""

set_smoketest_url = false
set_artifact_url = false
failure = false

pipeline {
    agent {
        ecs {
            inheritFrom 'ec2-agent-trixie'
        }
    }

    environment {
        SONAR_CLOUD = credentials('sonar')
        BITBUCKET_AUTH = credentials('bitbucket_auth')
        BITBUCKET_ADMIN = credentials('bitbucket_admin')
    }

    stages {
        stage('Docker Build/Push') {
            steps {
                script{
                    stage_name = env.STAGE_NAME
                    echo "Running on ${NODE_NAME}"
                    bitbucketStatus repo: "${repo}", BRANCH_NAME: "${BRANCH_NAME}", GIT_COMMIT: "${GIT_COMMIT}", status: "INPROGRESS"
                    def build_job_result = build job: "MOP_Services/${repo}/build_${repo}_api", parameters: [
                        [$class: 'StringParameterValue', name: 'IMAGE_TYPE', value: "release"],
                        [$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH_NAME}"]
                    ], propagate: false, wait: true
                    build_status = build_job_result.getResult()

                    if("${build_status}" != "SUCCESS"){
                        child_url = build_job_result.getBuildVariables()['BUILD_LINK']
                        error "Build Step failed"
                    }
                    STAGING_IMAGE = build_job_result.getBuildVariables()["ECR_TAG"]
                    commit_hash = STAGING_IMAGE.split("-")[0]
                    echo "Staging Image: ${STAGING_IMAGE}"
                }
            }
        }

       stage('Generate and Upload SBOM') {
           steps {
               script {
                   try {
                       generateAndUploadSBOM(repo)
                   } catch (Exception e) {
                       echo "SBOM generation failed: ${e.getMessage()}"
                   }
               }
           }
       }

        stage('Deploy to Sandbox'){
            steps{
                script{
                    stage_name = env.STAGE_NAME
                    build_job = build job: "MOP_Services/${repo}/deploy_${repo}_api", parameters: [
                        [$class: 'StringParameterValue', name: 'ENVIRONMENT', value: "sandbox"],
                        [$class: 'StringParameterValue', name: 'IMAGE_TAG', value: "${STAGING_IMAGE}"]
                    ], propagate: false, wait: true
                    build_status = build_job.getResult()

                    if( "${build_status}" == "SUCCESS" ){
                        author_email = fetch_author_email("${repo}", "${commit_hash}")
                        fn_msg = "Merged changes are now deployed to sandbox, commit_hash: ${commit_hash}, Image: ${STAGING_IMAGE}"
                        send_custom_notification("${author_email}", "${repo}", "cd-mop-staging", "${fn_msg}", "good", " ")
                    }else{
                        child_url = build_job.getBuildVariables()['BUILD_LINK']
                        error "Deploy to Sandbox failed"
                    }
                    sleep 60
                }
            }
        }

        stage('Taurus Tests') {
            steps {
                script {
                    stage_name = env.STAGE_NAME
                    (set_artifact_url, set_smoketest_url, artifact_link, smoketest_url, failure, failure_msg) = taurus_tests("sandbox", repo, set_artifact_url, set_smoketest_url, artifact_link, smoketest_url, failure_msg)
                     if(failure == true){
                         error "Taurus tests failed"
                     }
                     sleep 10
                }
            }
        }

        stage('Flyway Migration') {
            steps {
                script {
                    stage_name = env.STAGE_NAME
                    dep_environment = "staging"
                    flyway_migration_merge("${repo}", "${dep_environment}")
                }
            }
        }

        stage('Deploy to Staging'){
            steps{
                script{
                    sleep 10
                    stage_name = env.STAGE_NAME
                    build_job = build job: "MOP_Services/${repo}/deploy_${repo}_api", parameters: [
                        [$class: 'StringParameterValue', name: 'ENVIRONMENT', value: "staging"],
                        [$class: 'StringParameterValue', name: 'IMAGE_TAG', value: "${STAGING_IMAGE}"]
                    ], propagate: false, wait: true
                    build_status = build_job.getResult()

                    if( "${build_status}" == "SUCCESS" ){
                        author_email = fetch_author_email("${repo}", "${commit_hash}")
                        fn_msg = "Merged changes are now deployed to staging, commit_hash: ${commit_hash}, Image: ${STAGING_IMAGE}"
                        send_custom_notification("${author_email}", "${repo}", "cd-mop-staging", "${fn_msg}", "good", " ")
                    }else{
                        child_url = build_job.getBuildVariables()['BUILD_LINK']
                        error "Deploy to Staging failed"
                    }
                }
            }
        }

    }

    post {
        always {
            sh "rm -rf ${MVN_HOME}/${BUILD_NUMBER}"
        }
        aborted {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, PR_CHECK: "false", status: "STOPPED"
        }
        failure {
            script{
                bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, PR_CHECK: "false", status: "FAILED"
                if(set_smoketest_url == true) {
                    link_url = link_url+", [Smoketest Kibana Link](${smoketest_url})"
                }
                if (set_artifact_url == true) {
                    link_url = link_url+", [RequestResponse URL](${artifact_link})"
                }

                currentDeployedCommit = fetch_current_deployed_container("${repo}", "${dep_environment}")
                currentDeployedCommit = currentDeployedCommit.split("-")[0]
                dlink = "https://bitbucket.org/netfoundry/${repo}/branches/compare/${commit_hash}..${currentDeployedCommit}#pull-requests"
                if(currentDeployedCommit != commit_hash) {
                    link_url = link_url+", [Git Diff Link](${dlink})"
                }
                if ("${build_status}" != "SUCCESS"){
                    link_url = link_url+", [Failed Build URL](${child_url})"
                    echo "Failed Build URL: ${child_url}"
                }
                mattermostFailureNotification repo: "${repo}", commit: GIT_COMMIT, build_url: RUN_DISPLAY_URL, channel: "cd-mop-staging", link_url: "${link_url}", reason: "Promotion of image ${STAGING_IMAGE} to ${dep_environment} failed at stage ${stage_name}. Please check link for details."
            }
        }
        success {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, PR_CHECK: "false", status: "SUCCESSFUL"
        }
    }
}