def main() {
    stage("Checkout") {
            container("python") { sh("chown -R 1000:1000 ./") }
            checkout(changelog: false, poll: false, scm: [
                $class           : "GitSCM",
                branches         : [[name: "*/tools"]],
                userRemoteConfigs: [[url: "https://github.com/tidbcloud/test-automation.git",
                                    credentialsId: "github-sre-bot"]],
                extensions       : [[$class: 'PruneStaleBranch'], [$class: 'CleanBeforeCheckout']],
            ])
        }

    stage("Initialize environment"){
            echo "start to update pip"
            container('python'){
                sh("""
                    mkdir  ~/.pip/
                    touch  ~/.pip/pip.conf
                    echo '[global]\nindex-url=http://mirrors.aliyun.com/pypi/simple/\n[install]\ntrusted-host=mirrors.aliyun.com' > ~/.pip/pip.conf
                """)
                echo "start to install dependencies"
                sh("""
                    pip3 install -r requirements.txt
                """)
                echo "finish dependencies"

            }
        }

    stage("Test") {
            container("python") {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
                    echo "initial crendtial"
                    withCredentials([usernamePassword(credentialsId: "${params.user}"+"-aws", usernameVariable: "username", passwordVariable: "password")]){
                        echo " ------------ set credential ------------"
                        sh "python  set_credential.py --account=${params.user} --accessId=$username --secretKey=$password"
                    }
                    echo "test execution"
                    sh("""
                        if [ "${params.operation}" = "add" ];then
                            echo "------------ add resources start ------------"
                            python add_resource.py --account=${params.user}
                        fi
                        if [ "${params.operation}" = "clear" ];then
                            echo "------------ clear start ------------"
                            python clear_resource.py --account=${params.user}
                        fi
                        """)
                }
            }
        }
}

def run(label, image, Closure body) {
    podTemplate(name: label, label: label, instanceCap: 10,  containers: [
        containerTemplate(name: 'python', image: image, alwaysPullImage: true, ttyEnabled: true, command: 'cat'),
    ]) { node(label) { body() } }
}

catchError {
    run("UI-Test-Automation-${BUILD_NUMBER}", 'python:3.8-buster') { main() }
}