def main() {
stage("Checkout") {
            container("python") { sh("chown -R 1000:1000 ./") }

            checkout(changelog: false, poll: false, scm: [
                $class           : "GitSCM",
                branches         : [[name: "*/master"]],
                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("""
                    pip install --upgrade pip
                    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
                    pip3 install pytest-html
                    pip3 install allure-pytest
                """)
            }
        }

    stage("Test") {
        container("python") {
            catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
                echo "start to execute test"
                sh 'mkdir ./result/allure'
                sh 'python main.py --env=${environment}'
            }
        }
    }

    stage("Report") {
        container("python") {
            def url = "http://172.16.4.27:31090/view/dbaas/job/UI-Automation-Test"
            def projectDir = pwd()
            sh("""
                mkdir report
                chmod -R a+rw *
                export ALLURE_RESULTS_PATH=${projectDir}/report
                ls -al result/allure-results
            """)
            script {
                allure([
                    includeProperties: false,
                    jdk: 'DBaaS',
                    properties: [],
                    reportBuildPolicy: 'ALWAYS',
                    report: 'report/allure-report',
                    results: [[path:'result/allure-results']]
                    ])
            }
                   
            sh("""
                python notify.py Ui-Auto-Test ${environment} ${currentBuild.result} ${url}/${BUILD_NUMBER}/allure
                """)
                
        }

    }
}

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}", 'joyzoursky/python-chromedriver') { main() }
}
