import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import groovy.json.JsonSlurper;


node {
    def projectName =  determineRepoName()
    def projectGit = "Kushki/${projectName}"
    def ENVIRONMENT = ""
    def PULL_REQUEST = env.CHANGE_ID

    sh "echo ${projectName} - ${projectGit}"
       if ("${env.CHANGE_TARGET}".contains("release")) {
            ENVIRONMENT = "ci"
        }
        if ("${env.CHANGE_TARGET}".contains("master")) {
            ENVIRONMENT = "qa"
        }

        stage('Pull') {

             git branch: "${CHANGE_BRANCH}", url: "git@github.com:${projectGit}.git"
             sh "git rev-parse HEAD > .git/commit-id"
             commit_id = readFile('.git/commit-id')
             commit_id = commit_id.split("\n")[0]
             sh "aws ssm get-parameters --names /${ENVIRONMENT}/${projectName}/RUNSCOPE_SUITE_TEST --region us-east-1 --query \"Parameters[0].Value\" > .tmp"
             RUNSCOPE_SUITE_TEST  = readFile('.tmp')
             RUNSCOPE_SUITE_TEST = RUNSCOPE_SUITE_TEST.split("\n")[0]
             sh "aws ssm get-parameters --names /${ENVIRONMENT}/${projectName}/RUNSCOPE_ENV --region us-east-1 --query \"Parameters[0].Value\" > .tmp"
             RUNSCOPE_ENV  = readFile('.tmp')
             RUNSCOPE_ENV = RUNSCOPE_ENV.split("\n")[0]
             sh "git show --format='%ae' $commit_id  > .git/commit-author"
             GIT_AUTHOR_EMAIL  = readFile('.git/commit-author')
             GIT_AUTHOR_EMAIL = GIT_AUTHOR_EMAIL.split("\n")[0]
        }

        stage('Test and build') {
          parallel(
          createCIArtifact:{
          if ("${env.CHANGE_TARGET}".contains("release")) {
          withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
          awsCodeBuild artifactLocationOverride: 'artifact-build', artifactNameOverride: "${commit_id}.zip", artifactNamespaceOverride: "NONE", artifactPackagingOverride: 'ZIP', artifactPathOverride: "ci/${projectName}/PR${PULL_REQUEST}/", artifactTypeOverride: 'S3',  awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '10', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins',  envVariables: "[ { USRV_STAGE, ci }, {USRV_COMMIT, $commit_id}, {USRV_BRANCH,$CHANGE_BRANCH} ]", gitCloneDepthOverride: '', projectName: 'usrv_back_build', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'jenkins', sourceVersion: '', sseAlgorithm: 'AES256'
          }}},
          createSTGArtifact:{
          if ("${env.CHANGE_TARGET}".contains("master")) {
          withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
          awsCodeBuild artifactLocationOverride: 'artifact-build', artifactNameOverride: "${commit_id}.zip", artifactNamespaceOverride: "NONE", artifactPackagingOverride: 'ZIP', artifactPathOverride: "stg/${projectName}/PR${PULL_REQUEST}/", artifactTypeOverride: 'S3',  awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '10', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins',  envVariables: "[ { USRV_STAGE, stg }, {USRV_COMMIT, $commit_id}, {USRV_BRANCH,$CHANGE_BRANCH} ]", gitCloneDepthOverride: '', projectName: 'usrv_back_build', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'jenkins', sourceVersion: '', sseAlgorithm: 'AES256'
          }  }
          },
          createQAArtifact:{
          if ("${env.CHANGE_TARGET}".contains("master")) {
          withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
          awsCodeBuild artifactLocationOverride: 'artifact-build', artifactNameOverride: "${commit_id}.zip", artifactNamespaceOverride: "NONE", artifactPackagingOverride: 'ZIP', artifactPathOverride: "qa/${projectName}/PR${PULL_REQUEST}/", artifactTypeOverride: 'S3',  awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '10', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins',  envVariables: "[ { USRV_STAGE, qa }, {USRV_COMMIT, $commit_id}, {USRV_BRANCH,$CHANGE_BRANCH} ]", gitCloneDepthOverride: '', projectName: 'usrv_back_build', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'jenkins', sourceVersion: '', sseAlgorithm: 'AES256'
          }  }
          },
          testingCode:{
          withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
          awsCodeBuild artifactLocationOverride: '', artifactPathOverride: '', artifactTypeOverride: 'NO_ARTIFACTS', awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '60', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins', envParameters: '', envVariables: '', gitCloneDepthOverride: '', projectName: 'usrv_back_testing', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'jenkins', sourceVersion: '', sseAlgorithm: 'AES256'
          }
          },
         SonarQube_analysis: {
          withCredentials([string(credentialsId: 'GITHUB_SONAR_TOKEN', variable: 'GITHUB_SONAR_TOKEN'), string(credentialsId: 'SONAR_TOKEN', variable: 'SONAR_TOKEN')]) {
          sh "echo \"sonar.projectKey=${env.SONAR_TOKEN}\">> sonar-project.properties"
          sh "echo \"sonar.projectName=${projectName}\">> sonar-project.properties"
                           withSonarQubeEnv('sonarqubeServer') {
                           sh "/opt/sonarqube/sonar-cli/bin/sonar-scanner " +
                           "-Dsonar.github.repository=${projectGit} " +
                           "-Dsonar.analysis.mode=issues " +
                           "-Dsonar.github.pullRequest=${PULL_REQUEST} " +
                           "-Dsonar.github.oauth=${env.GITHUB_SONAR_TOKEN} " +
                           "-Dsonar.host.url=http://sonarqube.kushkipagos.com " +
                           "-Dsonar.login=${env.SONAR_TOKEN} -X"
                           }
          }
          }

          )
        }

        stage ("deploy $ENVIRONMENT") {
        withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
        awsCodeBuild artifactLocationOverride: '', artifactNameOverride: '', artifactNamespaceOverride: '', artifactPackagingOverride: '', artifactPathOverride: '', artifactTypeOverride: 'NO_ARTIFACTS', awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '10', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins', envParameters: '', envVariables: "[{ USRV_STAGE, $ENVIRONMENT }, {USRV_COMMIT, $commit_id}, {USRV_BRANCH,$CHANGE_BRANCH}, { ARTIFACT, s3://artifact-build/$ENVIRONMENT/${projectName}/PR${PULL_REQUEST}/${commit_id}.zip }]", gitCloneDepthOverride: '', projectName: 'usrv_back_deploy', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'project', sourceVersion: '', sseAlgorithm: 'AES256'
        }

        }
        notifyRollbar(ENVIRONMENT,projectName, commit_id, GIT_AUTHOR_EMAIL)
        stage('Integration') {
        functionalTests()
        }
        if ("${env.CHANGE_TARGET}".contains("master")) {
         ENVIRONMENT = "stg"
           stage ("deploy $ENVIRONMENT") {
           withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
           awsCodeBuild artifactLocationOverride: '', artifactNameOverride: '', artifactNamespaceOverride: '', artifactPackagingOverride: '', artifactPathOverride: '', artifactTypeOverride: 'NO_ARTIFACTS', awsAccessKey: 'awsUser', awsSecretKey: "$awsUser", buildSpecFile: '', buildTimeoutOverride: '10', credentialsId: 'awsCodeBuildCredentialOK', credentialsType: 'jenkins', envParameters: '', envVariables: "[{ USRV_STAGE, $ENVIRONMENT }, {USRV_COMMIT, $commit_id}, {USRV_BRANCH,$CHANGE_BRANCH}, { ARTIFACT, s3://artifact-build/$ENVIRONMENT/${projectName}/PR${PULL_REQUEST}/${commit_id}.zip }]", gitCloneDepthOverride: '', projectName: 'usrv_back_deploy', proxyHost: '', proxyPort: '', region: 'us-east-1', sourceControlType: 'project', sourceVersion: '', sseAlgorithm: 'AES256'
           }
           notifyRollbar(ENVIRONMENT,projectName, commit_id, GIT_AUTHOR_EMAIL)
        }

    }
    }


String determineRepoName() {
    return "${env.JOB_NAME}".tokenize('/')[1]
}

def functionalTests() {
   timeout(time: 300, unit: 'SECONDS') {


            hook = registerWebhook()
            def wurl = "https://api.runscope.com/radar/${RUNSCOPE_SUITE_TEST}/trigger"

            sh """
                curl -X GET ${wurl} \
                -d runscope_environment=${RUNSCOPE_ENV} \
                -d runscope_notification_url=${hook.getURL()}
            """
        def dataAsstring = waitForWebhook hook
        def props = readJSON text: dataAsstring.substring(0,dataAsstring.indexOf("test_run_id")-1) + "}"
        echo "Review : ${props.test_run_url}"
        assert (props.result == "pass") : "Runscope fail! ಥ_ಥ. better luck next time"
        echo "Hi :) : everything is gonna be alright"
        }
    }


def notifyRollbar(String environment, String projectName, String commit_id, String GIT_AUTHOR_EMAIL ){

             sh "aws ssm get-parameters --names /${environment}/${projectName}/ROLLBAR_TOKEN --region us-east-1 --query \"Parameters[0].Value\" > .tmp"
             def ROLLBAR_TOKEN  = readFile('.tmp')
             ROLLBAR_TOKEN = ROLLBAR_TOKEN.split("\n")[0]
             stage('Notify Rollbar') {
             withCredentials([ string(credentialsId: 'awsUser', variable: 'awsUser')]) {
       sh """
                curl --fail -X POST https://api.rollbar.com/api/1/deploy/ \
                   -F access_token=$ROLLBAR_TOKEN \
                   -F environment=$environment \
                   -F revision=$commit_id \
                   -F local_username=$GIT_AUTHOR_EMAIL
            """
        }
        }

}
