@Library('nf-jenkins-shared-libraries@master')_
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import jenkins.model.Jenkins
import hudson.model.*
import hudson.tasks.test.*
import groovy.xml.XmlUtil
import org.json.JSONObject
import org.json.XML

CURRENT_GIT_HASH = ""
DEPLOYED_GIT_HASH = ""

repo = "reporting-templates"
dep_environment = "sandbox"

stage_name = ""

url_es_array = [
    "sandbox": "https://671f1b395ca2c86a99dca8c10d455c61.us-east-1.aws.found.io:9243/",
    "staging": "https://cded6653d25e80c7af745be8686cbf05.us-east-1.aws.found.io:9243/"
]

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

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

    stages {
        stage('Initialize') {
            steps {
                script {
                    stage_name = env.STAGE_NAME
                    CURRENT_GIT_HASH = sh(returnStdout: true, script: "git rev-parse --short HEAD").trim()
                    echo "Current hash is: ${CURRENT_GIT_HASH}"
                }
            }
        }

        stage('Deploy to sandbox') {
            steps {
                script {
                    stage_name = env.STAGE_NAME
                    path = "/${dep_environment}/reporting-templates"
                    DEPLOYED_GIT_HASH = read_ssm_path(dep_environment, path)
                    echo "Currently deployed hash is: ${DEPLOYED_GIT_HASH}"

                    sh "git diff --name-status ${CURRENT_GIT_HASH} ${DEPLOYED_GIT_HASH} > ${dep_environment}rtfileslist.txt"
                    def rtfiles = readFile("./${dep_environment}rtfileslist.txt").readLines()
                    echo "${rtfiles}"

                    for(String rtfile: rtfiles) {
                        if( ! rtfile.toString().contains("jenkinsfiles")) {
                            def flag = sh(returnStdout: true, script: """echo ${rtfile} | awk '{print \$1}'""").trim()
                            def rtfilePath = sh(returnStdout: true, script: """echo ${rtfile} | awk '{print \$2}'""").trim()
                            def identifier = sh(returnStdout: true, script: """basename ${rtfilePath}""").trim().split("\\.")[0]

                            if("${flag}" == "D"){
                                remove_template(dep_environment, identifier)
                            } else if ("${flag}" == "A" || "${flag}" == "M"){
                                update_template(dep_environment, identifier, rtfilePath)
                            }
                        }
                    }
                    record_ssm_path(dep_environment, path, CURRENT_GIT_HASH)
                    echo "Hash ${CURRENT_GIT_HASH} deployed successfully"
                }
            }
        }

        stage('Deploy to staging') {
            steps {
                script {
                    stage_name = env.STAGE_NAME
                    dep_environment = "staging"

                    path = "/${dep_environment}/reporting-templates"
                    DEPLOYED_GIT_HASH = read_ssm_path(dep_environment, path)
                    echo "Currently deployed hash is: ${DEPLOYED_GIT_HASH}"

                    sh "git diff --name-status ${CURRENT_GIT_HASH} ${DEPLOYED_GIT_HASH} > ${dep_environment}rtfileslist.txt"
                    def rtfiles = readFile("./${dep_environment}rtfileslist.txt").readLines()
                    echo "${rtfiles}"

                    for(String rtfile: rtfiles) {
                        if( ! rtfile.toString().contains("jenkinsfiles")) {
                            def flag = sh(returnStdout: true, script: """echo ${rtfile} | awk '{print \$1}'""").trim()
                            def rtfilePath = sh(returnStdout: true, script: """echo ${rtfile} | awk '{print \$2}'""").trim()
                            def identifier = sh(returnStdout: true, script: """basename ${rtfilePath}""").trim().split("\\.")[0]

                            if("${flag}" == "D"){
                                remove_script(dep_environment, identifier)
                            } else if ("${flag}" == "A" || "${flag}" == "M"){
                                update_script(dep_environment, identifier, rtfilePath)
                            }
                        }
                    }
                    record_ssm_path(dep_environment, path, CURRENT_GIT_HASH)
                    echo "Hash ${CURRENT_GIT_HASH} deployed successfully"
                }
            }
        }
    }

    post {
        always {
            script {
                echo "build completed"
            }
        }
        failure {
            script {
                echo "${repo} deploy failed at ${stage_name}."
            }
        }
        success {
            script {
                echo "${repo} deploy Succeeded"
            }
        }
    }
}

def update_template(environment, identifier, dataFilePath){
    withCredentials([usernamePassword(credentialsId: "jenkins_template_reader_${environment}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        def userpass = USERNAME + ":" + PASSWORD
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        headers = [
            [
                name:  'Authorization',
                value: basicAuth,
                maskValue: true
            ]
        ]

        def es = url_es_array[environment] +"__scripts/${identifier}"
        //def jsonData = new JsonBuilder( data ).toPrettyString()
        def jsonData = readJSON file: "${dataFilePath}"

        def response = httpRequest(
                url: es,
                requestBody: jsonData,
                httpMode: 'PUT',
                timeout: 60,
                customHeaders: headers,
                consoleLogResponseBody: true,
                contentType: 'APPLICATION_JSON'
        )
        println response
    }
}

def remove_template(environment, identifier){
    withCredentials([usernamePassword(credentialsId: "jenkins_template_reader_${environment}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
        def userpass = USERNAME + ":" + PASSWORD
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        def es = url_es_array[environment] +"__scripts/${identifier}"
        headers = [
            [
                name:  'Authorization',
                value: basicAuth,
                maskValue: true
            ]
        ]

        def response = httpRequest(
                url: es,
                httpMode: 'DELETE',
                timeout: 60,
                customHeaders: headers,
                consoleLogResponseBody: true,
                contentType: 'APPLICATION_JSON'
        )
        println response
    }
}