@Library('terraform-infra@main') _

pipeline {
    agent {
        node {
            label 'slave-01'
        }
    }

    options {
        timestamps()
        ansiColor('xterm')
    }

    environment {
        GITHUB_CRED = 'meesho-jenkins'
    }

    stages {
        stage('Setup parameters') {
            steps {
                script {
                    properties([
                        parameters([
                            string(
                                defaultValue: '',
                                name: 'bu',
                                description: 'please enter the bu name',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'team',
                                description: 'please enter the team name',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'priority',
                                description: 'please enter the team name',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'approver1',
                                description: 'please enter the approver name',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'approver2',
                                description: 'please enter the second approver name',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'service',
                                description: 'K8s Service/app name. Example: supplier-payment-web, ads-credit ',
                                trim: true
                            ),
                            choice(
                                choices: ['critical', 'warning'],
                                description: 'NOTE: This is required',
                                name: 'severity'
                            ),
                            string(
                                defaultValue: '',
                                name: 'alert_name',
                                description: 'Metric to be onbaorded to Alertmanager. Please use capital letters and underscore (_) only and don’t use spaces ( ). Example: HTTP_4XX_Alert_Per_API',
                                trim: true
                            ),
                            string(
                                defaultValue: '',
                                name: 'query',
                                description: 'Copy the PromQL Query from existing Grafana Dashboard and paste it here',
                                trim: true
                            ),
                            choice(
                                choices: ['>=', '>', '=', '<=', '<'],
                                description: 'NOTE: This is required',
                                name: 'comparison_operator'
                            ),
                            choice(
                                choices: ['prd', 'ftr', 'dev', 'int'],
                                description: 'NOTE: This is required',
                                name: 'environment'
                            ),
                            string(
                                defaultValue: '',
                                name: 'threshold',
                                description: 'Threshold value of alerting. Example: 100, 200, 0.75 etc',
                                trim: true
                            ),
                            choice(
                                choices: ['1m', '2m', '5m', '10m'],
                                description: 'NOTE: This is required. Default - 1m',
                                name: 'period'
                            )
                        ])
                    ])
                }
            }
        }

        stage('validation') {
            steps {
                script {
                    env.msg = 'Started service alert onboarding'
                    alert_name = alert_name.replaceAll("${service}", '')
                    alert_name = alert_name.replaceAll(' ', '_')
                    alert_name = alert_name.replaceAll('-', '_')
                    alert_name = alert_name.replaceAll('__', '_')
                    def metric_details = [
                            'alert_name': "${alert_name}_EKS",
                            'summary': "EKS ${alert_name} on {{ \$labels.service }}"
                    ]
                    env.alert_name = metric_details['alert_name']
                    env.summary = metric_details['summary']
                    env.int_env = 'main'

                    log.info("""
                        App BU Name - ${bu}
                        App team Name - ${team}
                        Approver1 Name - ${approver1}
                        Approver2 Name - ${approver2}
                        Threshold - ${threshold}
                        Service Name - ${service}
                        Severity - ${severity}
                        Comparison Operator - ${comparison_operator}
                        Env - ${environment}
                        Period - ${period}
                        Alert Name - ${env.alert_name}
                        Query - ${query}
                        Summary - ${env.summary}
                    """)
                    if (params.bu.isEmpty() || params.team.isEmpty() || params.threshold.isEmpty() || params.service.isEmpty()) {
                        env.msg += '\n\nFAILED -\n  One or more input paramters are EMPTY/NULL.'
                        log.err("${env.msg}")
                    }
                }
            }
        }

        stage('Checkout Terraform-Infra repo') {
            steps {
                script {
                    log.info('Checkout Terraform-Infra repo')
                    gitActions.checkout()
                    env.msg += '\n2. Terraform-Infra Repo checkout step was SUCCESSFUL.'
                    // gitActions.branchCheckOut("${WORKSPACE}/${repo_name}", "${branch_name}")
                }
            }
        }


        stage('Create alert-config.yaml') {
            steps {
                script {
                    try {
                        log.info('Creating alert-config.yaml')
                        create_config()
                        env.msg += '\n4. Create alert-config.yaml step was SUCCESSFUL.'
                    }
                    catch (Exception e) {
                        env.msg += "\n\nFAILED -\n  Error while creating the alert-config.yaml.\n  Full Error Details - ${e}"
                        log.err("${env.msg}")
                    }
                }
            }
        }

        stage('Commit alert-config.yaml') {
            steps {
                script {
                    new_branch_name = "${bu}-${team}-${service}"
                    log.info("Pushing alert-config.yaml to Branch - ${new_branch_name}")
                    // log.info("Pushing alert-config.yaml to Branch - ${service}")
                    // sh "rm -rf ${repo_name}"
                    gitActions.branchCheckOut("${WORKSPACE}", "${new_branch_name}")
                    // gitActions.branchCheckOut("${WORKSPACE}", "${service}")
                    gitActions.add("${WORKSPACE}", '.')
                    gitActions.codeCommit("${WORKSPACE}", "${new_branch_name}", "Updated ${alert_name} for ${new_branch_name}")
                    gitActions.codePush("${WORKSPACE}", "${new_branch_name}")
                    // gitActions.codeCommit("${WORKSPACE}", "${service}", 'Updated alert-config.yaml')
                    // gitActions.codePush("${WORKSPACE}", "${service}")
                    env.msg += '\n5. Pushing alert-config.yaml step is SUCCESSFUL. Please make sure to delete branch after PR Merge.'
                }
            }
        }

        stage('Raising PR') {
            steps {
                script {
                    log.info("Creating PR -> Base - main; Head - ${new_branch_name}")
                    pr_message = "Onboarding Alerts for ${service}"
                    gitActions.createPR("${WORKSPACE}", 'terraform-infra', "${new_branch_name}", "${pr_message}")
                    env.msg += "\n6. Creating PR, Head - ${new_branch_name} and Base - main is SUCCESSFUL."
                }
            }
        }
    }
    post {
        always {
            cleanWs()
        }
        success {
            def buildNumber = env.BUILD_NUMBER
            def jobName = env.JOB_NAME
            def curlCommand = "curl -X POST -d '{"buildnumber": "$buildNumber", "jobName": "$jobName"}' http://10.21.148.142:8002/AddReviewersToPR"
            def response = sh(returnStdout: true, script: curlCommand)
            echo "Response: ${response}"
        }
    }
}

def create_config() {
    dir("${WORKSPACE}/meesho/tools/vm-alerts-config/configmap") {
        sh 'pwd'
        sh "mkdir -p ${bu}/${team}/${service}/custom_alerts"
        sh "touch ${bu}/${team}/${service}/custom_alerts/${service}-${alert_name}.yaml"

        def config_template = libraryResource 'com/meesho/template-app-alert-configmap.yaml'
        def config_binding = []

        config_binding = [
            'alert_name': "${env.alert_name}",
            'query': "${query}",
            'comparison_operator': "${comparison_operator}",
            'threshold': "${threshold}",
            'period': "${period}",
            'severity': "${severity}",
            'bu': "${bu}",
            'team': "${team}",
            'service': "${service}",
            'environment': "${environment}",
            'priority': "${priority}",
            'summary': "${env.summary}"
        ]
        writeFile file:"${bu}/${team}/${service}/custom_alerts/${service}-${alert_name}.yaml", text: tokenize(config_template, config_binding)

        sh "cat ${bu}/${team}/${service}/custom_alerts/${service}-${alert_name}.yaml"
        sh 'ls -al;ls -al ..'
    }
}
