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_online_credentials', variable: 'smoke_test_credentials')]) {
                        sh("python ${projectDir}/smoke_test/get_auth0_token.py --url=${params.URL}")
                    }
                    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("Checkout") {
        container("golang") { sh("chown -R 1000:1000 ./") }
        checkout(changelog: false, poll: false, scm: [
            $class           : "GitSCM",
            branches         : [[name: "*/master"]],
            userRemoteConfigs: [[url: "https://github.com/tidbcloud/qa-PlatformAPIAuto.git",
                                credentialsId: "github-sre-bot"]],
            extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
        ])
    }
    stage("Test") {
        container("golang") {
            def projectDir = pwd()
            catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
                sh("""
                    go env GOPRIVATE=github.com/tidbcloud
                    git --version
                    go env -w GOSUMDB=off
                """)
                withCredentials([usernamePassword(credentialsId: "qe-prod-patrol-github", usernameVariable: "username", passwordVariable: "password")]){
                        sh("git config --global url.'https://$username:$password@github.com'.insteadOf 'https://github.com'")
                }
                sh("""
                    go get -u github.com/tidbcloud/qa-Gourd
                    go mod tidy
                    cd ${projectDir}
                    mkdir report
                    export ALLURE_RESULTS_PATH=${projectDir}/report
                    cd sceneCases
                    go test -env pod -orgId ${params.ORGID} -CaseList "${params.SCOPE}" -requestUrl ${params.REQUESTURL} -redirectUrl ${params.REDIRECTURL} -timeout 180000s -parallel 5
                """)
            }
            sh("""
                chmod -R o+xw ${projectDir}/report
                mv  ${projectDir}/report /home/jenkins/agent/
            """)
        }
    }

    stage("Allure") {
            container("java") {
                //def projectDir = "/home/jenkins/agent"
                def projectDir = pwd()
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
                    sh("""
                        cd ${projectDir}
                        cp -r /home/jenkins/agent/report ./
                        cd /home/jenkins/agent/workspace/QE/platform-cluster-timeout-reminder/report/
                        export ALLURE_RESULTS_PATH=${projectDir}/report
                        chmod -R o+xw ${projectDir}/report

                    """)
                }
                script {
                    allure([
                        includeProperties: false,
                        jdk: 'openjdk:1.8',
                        properties: [],
                        reportBuildPolicy: 'ALWAYS',
                        report: 'report/allure-report',
                        results: [[path:'report/allure-results']]
                        ])
                }
            }

    }

    stage("Result") {
            container("python") {
               def projectDir = "/home/jenkins/agent"
               def url = "https://ci.pingcap.net/job/QE/job/platform-cluster-timeout-reminder"
               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-cluster-timeout-reminder ${currentBuild.result} ${url} ${BUILD_NUMBER}  prod reminder  ${params.RUNUSER}""")
               }

            }
        }
}

def run(label, image, Closure body) {
    podTemplate(name: label, label: label, instanceCap: 10, 
    nodeSelector: "kubernetes.io/arch=amd64",
    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'),
        containerTemplate(name: 'java', image: 'bincent/openjdk:1.8', alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
    ]) { node(label) { body() } }
}

catchError {
    run("platform-cluster-timeout-reminder-${BUILD_NUMBER}", 'golang:1.18.0') { main() }
}
