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
                """)
            }
        }

    stage("Test") {
        container("python") {
            catchError(buildResult: 'FAILURE', stageResult: 'FAILURE'){
            withCredentials([usernamePassword(credentialsId: "link-scan", usernameVariable: "username", passwordVariable: "password")]){
                sh("""
                        echo $username
                        echo $password
                        git clone -b master https://$username:$password@github.com/tidbcloud/dbaas-ui.git
                    """)
            }
            echo "start to execute test"
            sh("""
                python scanlink.py -white_list ${params.WHITE_LIST}
                """)
            }
        }
    }

    stage("Report") {
        container("python") {
            def url = "http://cicd.tidbcloud.com/view/Test/job/UI-Links-Detect"
            def projectDir = pwd()
            sh("""
                python notify.py UI-Links-Detect ${environment} ${currentBuild.result} ${BUILD_NUMBER} ${params.runBy} ${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-Links-Detect-${BUILD_NUMBER}", 'joyzoursky/python-chromedriver') { main() }
}
