properties([
        parameters([
                string(name: 'TIDB_HOST', defaultValue: '172.16.4.103', description: '', trim: true),
                string(name: 'TIDB_PORT', defaultValue: '4000', description: '', trim: true),
                string(name: 'TIDB_STATUS_PORT', defaultValue: '10080', description: '', trim: true),
                string(name: 'VERSION', defaultValue: '', description: '', trim: true),
        ])
])


def resourcePoolConfigFile = "resource-pool-config.yaml"
def valuesFile = "values.yaml"
def label = "execute-once"

def generateResoucePoolFile(file) {
    def content = """---
staticDBPool:
  - host: $params.TIDB_HOST
    port: $params.TIDB_PORT
    status_port: $params.TIDB_STATUS_PORT
    user: root
    pass: ''
    type: TiDB
    tags: ['$VERSION']
"""
    writeFile(file: file, text: content, encoding: "UTF-8")
}

def generateValuesFile(file) {
    def content = """---
casesDir: cases/
caseClasses:
  - simple/regression
"""
    writeFile(file: file, text: content, encoding: "UTF-8")
}

def notifyBuild(status) {
    if (status == null) {
        status = "SUCCESS"
    }
    def msg = """Job Name: ${env.JOB_NAME}
Build Number: ${env.BUILD_NUMBER}
Build Status: $status
Build URL: ${env.BUILD_URL}
"""
    slackSend(message: msg)
}

podTemplate(name: label, label: label, instanceCap: 5, idleMinutes: 60,
        containers: [
                containerTemplate(name: 'builder', image: 'hub.pingcap.net/jenkins/centos7_golang-1.13', alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
        ]) {
    node(label) {
        try {
            container("builder") {
                stage("build once") {
                    withCredentials([usernameColonPassword(credentialsId: params.getOrDefault("GH_CREDENTIAL", "github-sre-bot"), 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.getOrDefault("BRANCH", "master")]],
                                userRemoteConfigs: [[url          : "https://github.com/pingcap/qa.git",
                                                     credentialsId: params.getOrDefault("GH_CREDENTIAL", "github-sre-bot"),
                                                     refspec      : params.getOrDefault("REFSPEC", "+refs/heads/*:refs/remotes/origin/*")]],
                                extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
                        ])
                        dir("once") {
                            sh "make"
                        }
                    }
                }
                stage("start resource pool") {
                    dir("once/build") {
                        script {
                            generateResoucePoolFile(resourcePoolConfigFile)
                            sh "nohup timeout 1m bin/resource-pool -c $resourcePoolConfigFile &"
                        }
                    }
                }
                stage("execute once simple cases") {
                    dir("once/build") {
                        script {
                            generateValuesFile(valuesFile)
                            sh "RESOURCE_POOL_ENDPOINT=http://127.0.0.1:8080 bin/testkit run --template conf/template.yaml --values $valuesFile"
                        }
                    }
                }
            }
        } catch (e) {
            print(e)
        } finally {
            // notifyBuild(currentBuild.result)
        }
    }
}
