// properties([
//     parameters([
//         string(name: 'BRANCH', defaultValue: 'master', description: 'can be a commit id or pull request (format: pr/42)', trim: true),
//         string(name: 'REFSPEC', defaultValue: '+refs/heads/*:refs/remotes/origin/* +refs/pull/*/head:refs/remotes/origin/pr/*', description: '', trim: true),
//         credentials(name: 'CONFIG_FILE', defaultValue: 'qa-weekly-config', credentialType: 'org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl', description: '', required: true),
//         credentials(name: 'GH_CREDENTIAL', defaultValue: 'qa-jenkins-repo', credentialType: 'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl', description: '', required: true),
//     ])
// ])

def main() {
    stage("Checkout") {
        withCredentials([usernameColonPassword(credentialsId: params.GH_CREDENTIAL, variable: "GH_AUTH")]) {
            sh("""
            git config --global credential.helper store
            echo "https://$GH_AUTH@github.com > \$HOME/.git-credentials"
            """)
            checkout(changelog: false, poll: false, scm: [
                $class           : "GitSCM",
                branches         : [[name: params.BRANCH]],
                userRemoteConfigs: [[url: "https://github.com/pingcap/qa.git",
                                     credentialsId: params.GH_CREDENTIAL,
                                     refspec: params.REFSPEC]],
                extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
            ])
        }
    }
    stage("Generate Report") {
        container("golang") {
            withCredentials([
                file(credentialsId: params.CONFIG_FILE, variable: 'CONFIG_FILE'),
            ]) {
                dir("tools/qa-weekly") { 
                    sh("go run cmd/qa-weekly/main.go -c $CONFIG_FILE")
                    archiveArtifacts(artifacts: 'report-*.log', allowEmptyArchive: true)
                }
            }
        }
    }
}

def run(label, image, Closure main) {
    podTemplate(name: label, label: label, containers: [
        containerTemplate(name: 'golang', image: image, ttyEnabled: true, command: 'cat'),
    ]) { node(label) { main() } }
}

catchError {
    run('task-qa-weekly', 'hub.pingcap.net/jenkins/centos7_golang-1.13') { main() }
}

stage('Summary') {
    def duration = ((System.currentTimeMillis() - currentBuild.startTimeInMillis) / 1000 / 60).setScale(2, BigDecimal.ROUND_HALF_UP)
    def msg = "Build Result: `${currentBuild.currentResult}`" + "\n" +
              "Elapsed Time: `${duration} mins`" + "\n" +
              "${env.RUN_DISPLAY_URL}"

    echo "${msg}"

}
