properties([
    parameters([
        choice(name: 'BRANCH', choices: ["master", "release-4.0", "release-3.1", "release-3.0", "release-2.1"], description: 'release branch.'),
        string(name: 'PACKAGE_LIST', defaultValue: 'http://fileserver.pingcap.net/download/pingcap/qa/defaults/txn-cover.lst', description: 'package list url.', trim: true),
        booleanParam(name: 'WITH_TIKV', defaultValue: true, description: 'also test with tikv if available.'),
        // optional params
        string(name: 'PD_ARCHIVE', defaultValue: '', description: 'pd archive url, optional.', trim: true),
        string(name: 'TIKV_ARCHIVE', defaultValue: '', description: 'tikv archive url, optional.', trim: true),
    ])
])

def main() {
    stage("Checkout") {
        checkout(changelog: false, poll: false, scm: [
            $class           : "GitSCM",
            branches         : [[name: params.BRANCH]],
            userRemoteConfigs: [[url: "https://github.com/pingcap/tidb.git",
                                 credentialsId: params.GH_CREDENTIAL,
                                 refspec: params.REFSPEC]],
            extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
        ])
    }
    stage("Test") {
        container("tikit") {
            def test_cmd = "python3 -m tikit.ci.tidb cover-test --branch ${params.BRANCH}"
            if (!params.WITH_TIKV) { test_cmd += " --without-tikv" }
            if (params.PD_ARCHIVE) { test_cmd += " --pd-archive ${params.PD_ARCHIVE}" }
            if (params.TIKV_ARCHIVE) { test_cmd += " --tikv-archive ${params.TIKV_ARCHIVE}" }
            sh("${test_cmd} ${params.PACKAGE_LIST}")
        }
    }
    stage("Report") {
        container("tikit") {
            sh("python3 -m tikit.infra.fileserver upload pingcap/qa/reports/coverage/${env.BUILD_TAG}.html test.report.html")
        }
        archiveArtifacts(artifacts: "test.*.html,test.*.cover")
    }
}

def run(label, image, Closure main) {
    podTemplate(name: label, label: label, instanceCap: 5, idleMinutes: 60, containers: [
        containerTemplate(name: 'tikit', image: image, alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
    ]) { node(label) { dir("tidb") { main() } } }
}

catchError {
    run('test-tidb-coverage', 'hub.pingcap.net/zyguan/tidb-cover') { main() }
}
