#!groovy
/**
 * QA Release Declarative Pipeline with Shared library.
 *
 * 1. Static Analysis and Quality Gate check
 * 2. Deploy in QA Environment
 * 3. Test and generate report
 * 4. Send the report
 */
@Library('vplayed-cicd') _

def buildProps = ""
def approvalWithEmail = null
def module = ""

/**
 * Read build properties
 */
void readBuildProperties() {
    buildProps = readProperties file: 'build.properties'
}

pipeline {
    agent any
    stages {
        stage('Static Analysis') {
            steps {
                checkout scm
                withSonarQubeEnv('vplayed_sonarqube') {
                    runSonarScanner sonarProperties: "sonar-project.properties"
                    sleep 60
                }
            }
        }
        stage('Quality Gate') {
            steps {
                script {
                    def qg = waitForQualityGate()
                    if (qg.status != 'OK') {
                        // Send email and set the build status as failed

                        // Set Build Status
                        currentBuild.result = "FAILED"

                        // Read the build properties for developers email, and email template repo link
                        readBuildProperties()

                        // Send email to developers and ops team
                        // Send failure email with Sonarqube link attached
                        sendQGFailedEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}"

                        //Set build status as failed with a message
                        error "Pipeline aborted due to quality gate failure: ${qg.status}"
                    }
                }
            }
        }
        stage('Deploy') {
            agent {
                node {
                    label "Vplayed-QA"
                }
            }
            steps {
                script {
	            def DB_PASSWORD = 'CsitKcoAi1@'
	            def MAIL_SENDER_NAME = '"Balaganesh"'
                sh "echo '\n" +
                "APP_ENV=qa\n" +
                "ENABLE_SSL=true\n" +
                "APP_KEY=base64:6/uu9HYJh6dTFcY2cHBAoFpIQRuJc0tALiQdUu+rsZs=\n" +
                "APP_DEBUG=true\n" +
                "APP_LOG_LEVEL=debug\n" +
                "APP_URL=https://admin.vplayed.qa.contus.us\n" +
                "DB_HOST=192.168.0.53\n" +
                "DB_DATABASE=vplayed_qa\n" +
                "DB_USERNAME=vplayed_qa\n" +
                "DB_PASSWORD=${DB_PASSWORD}\n" +
                "\n" +
                "MONGODB_HOST=192.168.0.53\n" +
                "MONGODB_PORT=27017\n" +
                "MONGODB_DATABASE=vplayed_qa\n" +
                "MONGODB_USERNAME=root\n" +
                "MONGODB_PASSWORD=${DB_PASSWORD}\n" +
                "\n" +
                "BROADCAST_DRIVER=log\n" +
                "CACHE_DRIVER=redis\n" +
                "SESSION_DRIVER=file\n" +
                "\n" +
                "JWT_SECRET=l3GIk8O1GMgcIpOsOsVFd3u2KgoMy4bT\n" +
                "\n" +
                "BACKEND_API_PREFIX\n" +
                "LOG_CHANNEL=stack\n" +
                "\n" +
                "MAIL_DRIVER=smtp\n" +
                "MAIL_HOST=email-smtp.us-west-2.amazonaws.com\n" +
                "MAIL_PORT=587\n" +
                "MAIL_USERNAME=AKIAJMXVOSKU36XE4NKQ\n" +
                "MAIL_PASSWORD=AlmLrmzFS8hCaeXGnUmgAX3ZmfVfTXRHob6OcLzZHHEG\n" +
                "MAIL_ENCRYPTION=tls\n" +
                "MAIL_SENDER_ADDRESS=balaganesh.g@contus.in\n" +
                "MAIL_SENDER_NAME=${MAIL_SENDER_NAME}\n" +
                "\n" +
                "WEB_SITE_URL=https://vplayed.qa.contus.us/\n" +
                "WEB_SITE_AUDIO_URL=https://vplayed.audio.qa.contus.us/\n" +
                "API_URL=https://api.vplayed.qa.contus.us/\n" +
                "\n" +
                "AWS_VERSION=latest\n" +
                "AWS_SECRET=b07JnHIiA7t8QCPHzRViQ1o7gOZINRZUX+C3MG4W\n" +
                "AWS_REGION=ap-southeast-1\n" +
                "AWS_BUCKET=vplayed-uat\n" +
                "AWS_KEY=AKIAJRDHZDNJZG4Q6IOQ\n" +
                "AWS_BUCKET_URL=https://d1gqth3loa1oxy.cloudfront.net/\n" +
                "AWS_PIPELINE_ID=1543915792383-zac3gr\n" +
                "#TRANSCODE_LIMIT=0\n" +
                "VIDEO_TRANSCODE_TYPE=AWS\n" +
                "#VIDEO_TRANSCODE_TYPE=FFMPEG\n" +
                "\n" +
                "SCOUT_DRIVER=elastic\n" +
                "SCOUT_ELASTIC_HOST=localhost:9200\n" +
                "\n" +
                "WOWZA_API_PRODUCTION_URL=https://api.cloud.wowza.com/api/v1\n" +
                "WOWZA_CLOUD_API_KEY=QALQrsGO8NPvHIQ4Rz249bNx3XJjVBw3PK33XGWICsHpPPGMLkDWmY7w2Q972f5f\n" +
                "WOWZA_CLOUD_ACCESS_KEY=IZo6xdLviQVWOVJzH08fGEiNajSBK9f1aBC4ga0mOwIrbWYQEkDwt9geX9ne3349\n" +
                "WOWZA_BROADCAST_LOCATION=asia_pacific_singapore\n" +
                "FCM_KEY=AAAAkNJCt0g:APA91bGnKDJNUOJtIdL0Opj2A8FRiIsc0KWWCjnpfx7_xpAd-ihUpnHq9Y8EArZr6Rrw0fv8uQtEuY2HJet4KceARlZNazfFaYcNM4nMg7zjQpxnkQiF1EpojYe0IIBy7lO6en7Dj_cf\n" +
                "REDIS_HOST=192.168.0.53\n" +
                "REDIS_PASSWORD=null\n" +
                "REDIS_PORT=6379\n" +
                "REDIS_DB=1\n" +
                "GLOBAL_CACHE_TAG=vplayed_cache\n" +
                "GLOBAL_CACHE_TIME=120\n" +
                "ELASTICSEARCH_INDEX_PREFIX=qa_\n" +
                "DOWNLOAD_REFERER=https://vplayed.qa.contus.us/\n" +
                "NODE_URL=https://admin.api.vplayed.qa.contus.us/\n" +
                "ANALYTICS_VIEW_ID=182451440\n" +
                "#VIDEO_TRANSCODE_TYPE=TAAS\n" +
                "TAAS_UPLOAD_URL =http://192.168.0.201:8081/api/uploads?url=\n" +
                "TAAS_STATUS_URL =http://192.168.0.201:8081/api/TranscodeProcess/\n" +
                "VIDEO_LINGUAL_AUDIO_PRESET_ID = 1543817082256-v07q4y\n" +
                "' >.env" 
        sh 'composer install'
        sh 'chmod -R 777 storage bootstrap public'
        sh 'php artisan migrate --force'
        sh 'php artisan db:seed --force'
	    sh 'rm -f package-lock.json'
	    sh 'npm install'
        sh 'php artisan vendor:publish --all'
        sh 'cp -R packages/contus/base/src/resources/assets/ public/contus/base/'
        sh 'npm run dev'
        sh 'chmod -R 777 storage bootstrap public'
        sh 'rsync -a ./ /var/www/vplayed/html/admin/'
                }
            }
        }
        stage('Approval') {
            steps {
                checkout scm
                script {
                    // Read the build properties for developers email, and email template repo link
                    buildProps = readProperties file: 'build.properties'

                    /**
                     * Send email to OPS and Dev team - Build Ready for QA Process.
                     */
                    sendBuildForApprovalEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}"

                    /**
                     * Ask for approval to proceed for QA Process.
                     */
                    timeout(time: 1, unit: 'DAYS') { //Timeout in 1 day
                        approvalWithEmail = input id: 'approve_for_qa', message: 'Approve for QA Process', ok:
                                'Proceed', submitter: 'balaganesh.g@contus.in'
                    }
                    echo("Approval With Email: ${approvalWithEmail}");
                }
            }
        }
        stage("QA Process") {
            agent {
                node {
                    label "Vplayed-QA"
                }
            }
            steps {
                script {
                        /**
                         * Mandatory qmail.properties file check.
                         * Found: Send email to QA Team to start the QA process.
                         * Not found: Fail the build
                         */
                        def checkFileExist = fileExists 'qamail.properties'
                        if (checkFileExist) {
                            echo("true");
                            sendQaProcessEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}"
                        } else {
                            currentBuild.result = "FAILED"
                            currentBuild.description = "qamail.properties file not found"
                            error "qamail.properties file not found"
                        }

                        try {
                            /**
                             * Ask for approval to proceed for QA Process.
                             */
                            def qaStartInput
                            timeout(time: 4, unit: 'DAYS') { //Timeout in 4 days
                                qaStartInput = input id: 'qa_started', message: 'Ready to Start QA Process?', ok:
                                        'Yes', parameters: [choice(choices: ['Hours', 'Days'].join("\n"), description: '',
                                        name: 'Metric'), string(defaultValue: '1', description: '',
                                        name: 'Value')], submitter: 'balaganesh.g@contus.in,manikandan.guna@contus.in,ramankanth.v@contus.in,sangeethrajan.r@contus.in,krishnaraj.b@contus.in,sathishkumar.r@contus.in,venkatesh.s@contus.in,shanthini.b@contus.in,shanthini.b@contus.in,shivshankar.b@contus.in'
                            }

                            /**
                             * Send email to OPS and Dev team - QA Process started.
                             */
                            sendQaInitiatedEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}", value: "${qaStartInput['Value']}", metric:
                                    "${qaStartInput['Metric']}"

                            /**
                             * Approve/Decline the build, by Authorised QA person.
                             */
                            timeout(time: 5, unit: 'DAYS') { //Timeout in 5 days
                                input id: 'qa_approval', message: 'Approve the Build?', ok: 'I Approve', submitter:
                                        'balaganesh.g@contus.in,arunkumar.r@contus.in,manikandan.guna@contus.in,ramankanth.v@contus.in,sangeethrajan.r@contus.in,krishnaraj.b@contus.in,sathishkumar.r@contus.in,venkatesh.s@contus.in,shanthini.b@contus.in,shanthini.b@contus.in,shivshankar.b@contus.in,vinothini.d@contus.in'
                            }
                        } catch (err) {
                            if (err.toString().toLowerCase().contains("flowinterruptedexception")) {

                                // Send QA process failed email
                                sendQaFailedEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}"

                                currentBuild.result = "FAILURE"
                                error "QA Process Failed"
                            }
                        }
                        /**
                         * Send email to OPS and Dev team about the status.
                         */
                        sendQaPassedEmail to: "${buildProps['build.email.dev']}, ${buildProps['build.email.ops']}"
                }
            }
        }
    }
}
