@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: 'repo_name',
                                description: 'Repository name of the application. Example: supplier-payment, ads-credit etc',
                                trim: true
                            ),
                            string(
                                defaultValue: 'main',
                                name: 'branch_name',
                                description: 'Branch name of above provided repo. Example: master, develop',
                                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'
                            ),
                            choice(
                                choices: ['prd', 'ftr', 'dev', 'int'],
                                description: 'NOTE: This is required',
                                name: 'environment'
                            ),
                            choice(
                                choices: ['1m', '2m', '5m', '10m', '1h', '2h'],
                                description: 'NOTE: This is required. Default - 1m',
                                name: 'period'
                            )
                        ])
                    ])
                }
            }
        }

        stage('validation') {
            steps {
                script {
                    env.msg = 'Started service alert onboarding'
                    env.metric = 'CronJob_Alert'
                    env.int_env = 'main'
                    if (period.contains('m')) {
                        env.threshold = period.replaceAll('m', '').toInteger() * 60
                    }
                    else if (period.contains('h')) {
                        env.threshold = period.replaceAll('h', '').toInteger() * 60 * 60
                    }
                    else {
                        env.threshold = null
                    }
                    log.info("""
                        App Repo Name - ${repo_name}
                        App Repo Branch Name - ${branch_name}
                        Threshold - ${env.threshold}
                        Service Name - ${service}
                        Severity - ${severity}
                        Env - ${environment}
                        Period - ${period}
                    """)
                    if (params.repo_name.isEmpty() || params.branch_name.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('Clone service repo for fetching app details') {
            steps {
                script {
                    log.info("Cloning App Repo - ${repo_name}, Branch - ${branch_name}")
                    gitActions.clone("${WORKSPACE}", "${repo_name}", "${branch_name}")
                    // sh 'ls -al'
                    env.msg += '\n3. Service Repo Clone step was SUCCESSFUL.'
                    // gitActions.branchCheckOut("${WORKSPACE}/${repo_name}", "${branch_name}")
                }
            }
        }

        stage('Collecting app details') {
            steps {
                script {
                    dir("${repo_name}/deployments/") {
                        sh 'ls -al'
                        try {
                            def i = 0
                            log.info("Reading BU, Team etc from ${repo_name}/deployments/${service}.yaml")
                            cron = sh(returnStdout: true, script: "yq '.cron' ${service}.yaml").trim()
                            if (!cron.toBoolean()) {
                                env.msg += '\nProvided service is not a Scheduler/Cron Type.'
                                sh 'exit 1'
                            }
                            bu = sh(returnStdout: true, script: "yq '.bu' ${service}.yaml").trim()
                            team = sh(returnStdout: true, script: "yq '.team' ${service}.yaml").trim()
                            priority = sh(returnStdout: true, script: "yq '.priority' ${service}.yaml").trim()
                            cronjobs = sh(returnStdout: true, script: "yq '.environment.${environment}.jobs | keys' ${service}.yaml | sed 's/- //g' | tail -n 1").trim()
                            echo "${cronjobs}"
                            while (i <= cronjobs.toInteger()) {
                                cronjob_name = sh(returnStdout: true, script: "yq '.environment.${environment}.jobs[${i}] | keys' ${service}.yaml | sed 's/- //g'").trim()                                
                                echo "${cronjob_name}"
                                cronjob_name = cronjob_name.replaceAll('-', '_')
                                log.info("Creating alert-config.yaml for ${i}. ${cronjob_name}")
                                create_config()
                                i += 1
                            }
                        }
                        catch (Exception e) {
                            env.msg += "\n\nFAILED -\n  Error while fetching app details from the app repo provided.\n  Full Error Details - ${e}"
                            log.err("${env.msg}")
                        }
                    }
                }
            }
        }

        // 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 ${env.metric} 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()
        }
    }
}

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

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

        config_binding = [
            'threshold': "${env.threshold}",
            'cronjob_name': "${cronjob_name}",
            'period': "${period}",
            'severity': "${severity}",
            'bu': "${bu}",
            'team': "${team}",
            'service': "${service}",
            'environment': "${environment}",
            'priority': "${priority}",
        ]
        writeFile file:"${bu}/${team}/${service}/mandatory_alerts/${cronjob_name}-${env.metric}.yaml", text: tokenize(config_template, config_binding)

        sh "cat ${bu}/${team}/${service}/mandatory_alerts/${cronjob_name}-${env.metric}.yaml"
        sh "pwd;ls -al ${bu}/${team}/${service}/mandatory_alerts;ls -al .."
    }
}
