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

def repo = "customer-management"
def task_role = "${repo}-service-task-role"
def ecs_cluster = "ecs-cluster-nfn-internal-env-private"
def ecs_service = "ecs-${repo}-service"
def family = "tf_${repo}-service_td"

BUILD_LINK = ""

channel = "cd-mop-staging"
color = "good"
tf_version = "1.1.7"
failure = false

startedUserId = ""
link_url = "" //should be of the form "[LinkName](/url/path/)"
fn_msg = ""

pipeline {
    agent {
        ecs {
            inheritFrom 'agent-jdk17'
        }
    }

    environment {
        ELASTICSEARCH = credentials('elasticsearch')
        BITBUCKET_AUTH = credentials('bitbucket_auth')
        BITBUCKET_ADMIN = credentials('bitbucket_admin')
    }

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['sandbox', 'staging', 'production'], description: 'Environment to deploy selected tag to')
        string(name: 'IMAGE_TAG', defaultValue: "Get from ${repo}_api_build", description: 'Tag to be deployed to selected environment')
    }

    stages {
        stage("Initialize"){
            steps{
                script{
                    if("${params.ENVIRONMENT}" == "production"){
                        channel = "cd-mop-production"
                    }

                    //Enable build container auth to Bitbucket
                    enableContainerAuthToBitbucket()
                }
            }

        }

        stage('Record SSM'){
            steps {
                script {
                    sh "echo \"${params.IMAGE_TAG}\""
                    record_ssm("${repo}", "${ENVIRONMENT}", "${params.IMAGE_TAG}")
                }
            }
        }

        stage('Deploy Terraform') {
            steps {
                script {
                    //get Task Definition
                    taskDefinition = get_td("${params.ENVIRONMENT}", "${ecs_service}", "${ecs_cluster}")

                    terraform directory: "terraform", environment: params.ENVIRONMENT, tfversion: "${tf_version}"
                    currentBuild.description = "ENV: ${params.ENVIRONMENT}\nIMAGE_TAG: ${params.IMAGE_TAG}"
                }
            }
        }

        stage('ECS Health') {
            steps {
                script {
                    //Next Task Definition
                    nexttd = get_next_td("${taskDefinition}")
                    sleep 60
                    check_deployed_ecs("${nexttd}", "${params.ENVIRONMENT}", "${ecs_service}", "${ecs_cluster}")
                }
            }
        }
    }

    post {
        always {
            script {
                env.BUILD_LINK = "${RUN_DISPLAY_URL}"
            }
        }

        failure {
            script {
                //If started by user
                if ( currentBuild.rawBuild.getCauses()[0].toString().contains('UserIdCause') ){
                    try{
                        startedUserId = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
                        fn_msg = "Promotion to ${params.ENVIRONMENT} failed. Please check link for details."
                        color = "danger"
                        send_custom_notification("${startedUserId}", "${repo}", "${channel}", "${fn_msg}", "${color}", "${link_url}")
                    }catch(e){
                        echo "Notification to user failed. Error: ${e}"
                    }
                }

                //Capture log to ElasticSearch
                failure = true
                if("${params.ENVIRONMENT}" != "sandbox"){
                    try{
                        log_commit_elasticsearch("${params.ENVIRONMENT}", "${repo}", "${params.IMAGE_TAG}", "${startedUserId}", failure)
                    } catch(e) {
                        echo "Capture log to ElasticSearch failed. Error: ${e}"
                    }
                }
            }
        }

        success {
            script{
                //If started by user
                if ( currentBuild.rawBuild.getCauses()[0].toString().contains('UserIdCause') ){
                    try{
                        startedUserId = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
                        fn_msg = "Promotion to ${params.ENVIRONMENT} was successful."
                        send_custom_notification("${startedUserId}", "${repo}", "${channel}", "${fn_msg}", "${color}", "${link_url}")
                    }catch(e){
                        echo "Notification to user failed. Error: ${e}"
                    }
                }

                //Capture log to ElasticSearch
                if("${params.ENVIRONMENT}" != "sandbox"){
                    try{
                        log_commit_elasticsearch("${params.ENVIRONMENT}", "${repo}", "${params.IMAGE_TAG}", "${startedUserId}", failure)
                    } catch(e) {
                        echo "Capture log to ElasticSearch failed. Error: ${e}"
                    }
                }
            }
        }
    }
}