// properties([
//     parameters([
//         string(name: 'ONCE_ARCHIEVE', defaultValue: 'http://fileserver.pingcap.net/download/pingcap/qa/archives/once-master.tar.gz', description: '', trim: true),
//         string(name: 'ONCE_TIDB_FILTER', defaultValue: '.', description: '', trim: true),
//         string(name: 'ONCE_CASE_FILTER', defaultValue: '.', description: '', trim: true),
//         string(name: 'ONCE_CASE_INDEX', defaultValue: '', description: '', trim: true),
//         string(name: 'ONCE_RESPOOL_CONF', defaultValue: '', description: '', trim: true),
//         string(name: 'ONCE_RESPOOL_ENDPOINT', defaultValue: 'http://172.16.4.61:30119', description: '', trim: true),
//         string(name: 'ONCE_SPEC_TEMPLATE', defaultValue: 'https://gist.github.com/zyguan/487d074737de2e31543c69e85441c419/raw/4f3bf67b31c8678d8f4e7f24f820ba9f9e9d1498/template.yaml', description: '', trim: true),
//     ])
// ])

def main() {
    
    def respool = params.getOrDefault("ONCE_RESPOOL_ENDPOINT", "http://172.16.4.61:30119")

    stage("Prepare") {
        deleteDir()

        container("golang") {
            sh("curl -sL ${params.getOrDefault("ONCE_ARCHIEVE", "http://fileserver.pingcap.net/download/pingcap/qa/archives/once-master.tar.gz")} | tar xz --strip-components 1")

            // resource pool
            if (params.getOrDefault("ONCE_RESPOOL_CONF", "") != "") {
                echo("launch local resource pool: ${params.ONCE_RESPOOL_CONF}")
                sh("""
                pkill resource-pool || true
                curl -o respool.yaml -L ${params.ONCE_RESPOOL_CONF}
                cat respool.yaml
                bin/resource-pool -c respool.yaml > respool.log &
                tail respool.log
                """)
                // NOTE: config should use default port
                respool = "http://127.0.0.1:8080"
            }

            // values
            def remote = false
            if (params.getOrDefault("ONCE_CASE_INDEX", "") != "") {
                echo("use remote case index")
                sh("curl -o cases.json ${params.ONCE_CASE_INDEX}")
                remote = true
            } else {
                sh("cp cases/index.json cases.json")
            }
            def tidbFilter = params.getOrDefault("ONCE_TIDB_FILTER", ".")
            def caseFilter = params.getOrDefault("ONCE_CASE_FILTER", ".")
            sh("""
            curl -o tidbs.json -L ${respool}/resource-pool/tidb
            jq  -s '{tidbs: [.[0][] | ${tidbFilter}], cases: [.[1][] | ${caseFilter}], remote: ${remote}}' tidbs.json cases.json > values.json
            cat values.json
            """)

            // spec
            sh("""
            curl -o template.yaml -L ${params.getOrDefault("ONCE_SPEC_TEMPLATE", "https://gist.github.com/zyguan/487d074737de2e31543c69e85441c419/raw/e37a6644629e5db66d009e1f2c0fc0432275eb33/template.yaml")}
            bin/testkit render --template template.yaml --values values.json > spec.yaml
            cat spec.yaml
            """)

        }
    }

    stage("Test") {
        container("golang") {
            try {
                sh("RESOURCE_POOL_ENDPOINT=${respool} bin/testkit run --spec spec.yaml")
            } catch(Exception e) {
                archiveArtifacts(artifacts: 'spec.yaml')
                archiveArtifacts(artifacts: 'values.json')
                sh("cat testkit.log")
                throw e
            }
        }
    }

}

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('once-lua-executor', '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}"

}
