def main() {

    stage("Checkout") {
            container("python") { sh("chown -R 1000:1000 ./") }

            checkout(changelog: false, poll: false, scm: [
                $class           : "GitSCM",
                branches         : [[name: "*/main"]],
                userRemoteConfigs: [[url: "https://github.com/tidbcloud/cloud-cicd.git",
                                    credentialsId: "github-sre-bot"]],
                extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
            ])
        }

    stage("GetToken") {
            container("selenium") {
                def projectDir = pwd()
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE'){
                    sh("cd ${projectDir}/smoke_test")
                    /*withCredentials([string(credentialsId: 'scene_staging_credentials', variable: 'smoke_test_credentials')]) {
                        sh("python ${projectDir}/smoke_test/get_auth0_token.py --url=${params.URL}")
                    }
                    withCredentials([string(credentialsId: 'scene_staging_recieve_password_credentials', variable: 'smoke_test_credentials')]) {
                        sh("python ${projectDir}/smoke_test/get_auth0_token.py --url=${params.URL}")
                    }
                    withCredentials([string(credentialsId: 'scene_staging_audit_credentials', variable: 'smoke_test_credentials')]) {
                        sh("python ${projectDir}/smoke_test/get_auth0_token.py --url=${params.URL}")
                    }*/
                    withCredentials([string(credentialsId: 'admin_staging_credentials', variable: 'smoke_test_credentials')]) {
                        sh("python ${projectDir}/smoke_test/get_auth0_token.py --url=https://ops-staging.tidbcloud.com")
                    }
                    sh("cp -r ${projectDir}/jenkins_notify/notify.py /home/jenkins/agent/")
                    sh("mv ${projectDir}/kafka_run /home/jenkins/agent/")
                }

                //archiveArtifacts(artifacts: "${projectDir}/sceneCases.tar.gz")

            }

        }
    /*stage("Run_kafka") {
             container("golang") {
                  def projectDir = "/home/jenkins/agent"
                      catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE'){
                           sh("""
                                cd ${projectDir}/kafka_run
                                go run main.go""")
                      }
             }
        }*/
    stage("Checkout") {
        container("golang") { sh("chown -R 1000:1000 ./") }
        checkout(changelog: false, poll: false, scm: [
            $class           : "GitSCM",
            branches         : [[name: "*/dev-test"]],
            userRemoteConfigs: [[url: "https://github.com/tidbcloud/qa-PlatformAPIAuto.git",
                                credentialsId: "github-sre-bot"]],
            extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
        ])
    }
    stage("Test") {
        container("golang") {
             withCredentials([usernamePassword(credentialsId: 'cdc_credentials', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                def projectDir = pwd()
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
                   sh("""
                     pwd
                     go env GOPRIVATE=github.com/tidbcloud
                    """)
                    withCredentials([usernamePassword(credentialsId: "qe-automation-github", usernameVariable: "usernameg", passwordVariable: "passwordg")]){
                            sh("git config --global url.'https://$usernameg:$passwordg@github.com'.insteadOf 'https://github.com'")
                    }
                    sh("""
                     go env -w GOSUMDB=off
                     go get -u github.com/tidbcloud/qa-Gourd
                     go mod tidy
                     cd ${projectDir}
                     mkdir report
                     export ALLURE_RESULTS_PATH=${projectDir}/report
                     cd sceneCases
                     if [ "${params.SCOPE}" = "all" ];then
                        go test -env staging -requestUrl "${params.REQUESTURL}" -orgId "${params.ORGID}" -projectId "${params.PROJECTID}" -tenantEmail "${params.TENANTEMAIL}" -spendLimits ${params.SPENDLIMITS} -serverlessTierClusterId "${params.serverlessTierClusterId}" -redirectUrl "${params.REDIRECTURL}" -recievePasswordEmail "${params.RecievePasswordEmail}" -AwsRegion "${params.AwsRegion}" -GcpRegion "${params.GcpRegion}" -RunUser "${params.RUNUSER}" -InfraImage "${params.InfraImage}" -FeatureGates "${params.FeatureGates}" -ExpFeatureGates "${params.ExpFeatureGates}" --timeout=18000s -parallel 5
                     else
                        go test -env staging -CaseList "${params.SCOPE}" -requestUrl "${params.REQUESTURL}" -orgId "${params.ORGID}" -projectId "${params.PROJECTID}" -tenantEmail "${params.TENANTEMAIL}" -spendLimits ${params.SPENDLIMITS} -redirectUrl "${params.REDIRECTURL}" -AwsRegion "${params.AwsRegion}" -GcpRegion "${params.GcpRegion}" -CPU "${params.CPU}" -HasTiflash "${params.HasTiflash}" -gcpClusterId "${params.gcpClusterId}" -awsClusterId "${params.awsClusterId}" -serverlessTierClusterId "${params.serverlessTierClusterId}" -port "${params.port}" -password "${params.password}" -RunUser "${params.RUNUSER}" -InfraImage "${params.InfraImage}" -FeatureGates "${params.FeatureGates}" -ExpFeatureGates "${params.ExpFeatureGates}" -RequireSecureTransport "${params.RequireSecureTransport}" -S3Accesskey ${env.USERNAME} -S3SecretKey ${env.PASSWORD} -timeout 180000s -parallel 5
                     fi
                     """)}
                sh("""
                    chmod -R o+xw ${projectDir}/report
                """)
             script {
                allure([
                   includeProperties: false,
                   jdk: 'DBaaS',
                   properties: [],
                   reportBuildPolicy: 'ALWAYS',
                   report: 'report/allure-report',
                   results: [[path:'report/allure-results']]
                ])
             }
          }


            //archiveArtifacts(artifacts: "${projectDir}/sceneCases.tar.gz")

        }

    }
    stage("Result") {
            container("python") {
               def projectDir = "/home/jenkins/agent"
               def url = "http://cicd.tidbcloud.com/view/Test/job/platform-scene-staging-test"
               catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE'){
               sh("""
                    cd ${projectDir}
                    ls
                    pip install --upgrade pip
                    pip install requests
                    pip install jira
                    pip install PyMySQL
                    python notify.py platform-scene-test-staging ${currentBuild.result} ${url} ${BUILD_NUMBER}  staging scene  ${params.RUNUSER} """)
               }

            }
        }
    /*stage("Image") {
        build(job: "image-build", parameters: [
            string(name: "CONTEXT_ARTIFACT", value: "$JOB_NAME:$BUILD_NUMBER:platfromCases/scene.tar.gz"),
            string(name: "DESTINATION", value: "hub.pingcap.net/qa/platfromCases"),
        ])
    }*/
}

def run(label, image, Closure body) {
    podTemplate(name: label, label: label, instanceCap: 10, containers: [
        containerTemplate(name: 'golang', image: image, alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
        containerTemplate(name: 'selenium', image: 'elgalu/selenium', alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
        containerTemplate(name: 'python', image: 'python:3.8', alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
    ]) { node(label) { body() } }
}

catchError {
    run("platform-scene-test-${BUILD_NUMBER}", 'golang:1.18.0') { main() }
}
