import java.text.*
import java.lang.*

//====================================================
// title          :jenkinsfile
// description    :regular full compilation
// author         :rock.jiang@cixtech.com
// date           :2024-01-18
// version        :1.0
// usage          :jenkins pipeline
// notes          :manifest repo
//=====================================================

def SendCiMail(String JOB_NAME, String BUILD_NUMBER, String BUILD_URL) {
    mail(
    from: 'devops@cixcomputing.com',
    to: 'rock.jiang@cixtech.com',
    // bcc: 'cai.xu@cixcomputing.com, anthony.tian@cixtech.com, robin.shen@cixtech.com, xinjun.cheng@cixtech.com',
    subject: "Build and Clean CI: Project ${currentBuild.result} ${BUILD_URL}",
    mimeType: 'text/html',
    charset: 'UTF-8',
    body: """
        <H1>Build ${currentBuild.result}</H1><BR/>
        <H2>Job Info:</H2><BR/>
        <B>Project:</B> ${JOB_NAME} <BR/>
        <B>Build Number:</B> ${BUILD_NUMBER} <BR/>
        <B>URL of build:</B> ${BUILD_URL} <BR/>
        """)
}
def formattedDate = new Date().format("yyyy-MM-dd-HH-mm-ss")
def CixMainLastXmlFileName = "cix_last_manifest_list.xml"
def CixMainDiffXmlFileName = "${formattedDate}-diff.log"

pipeline{
    options {
        timestamps()
    }
    agent { label "$params.AGENT_LABEL" }
    parameters {
    string(name: 'TEST_INDEX', defaultValue: 'none',
            description: "run the case with the specified index, such as 1,2")
    string(name: 'TEST_NAME', defaultValue: 'none', description: 'run the case with the specified test case name,such as docker_build_and_clean_all_sec_serial')
    choice(name: 'ALL_TEST', choices: ['-a', 'none'], description: "run all case")
    string(name: 'URL', defaultValue:'ssh://git@gitmirror.cixcomputing.com/linux_repo/cix-manifest', description: 'source code url')
    string(name: 'BRANCH', defaultValue: "cix_master", description: 'source code branch')
    string(name: 'MANIFEST', defaultValue: 'default.xml', description: "source code manifest")
    string(name: 'GROUPS', defaultValue: 'cix,notdefault,ddk,sec', description: "source code groups")
    string(name: 'YAML_CONFIG', defaultValue: 'linux_build_test_config', description: "Yaml name of test config")
    string(name: 'NEXUS_URL', defaultValue: 'None', description: "the nexus url of release rootfs.ext4")
    string(name: 'AGENT_LABEL', defaultValue: 'daily', description: "Label of the agent node to use")
    }
    environment{
        CASE_INDEX = "$params.TEST_INDEX"
        CASE_NAME = "$params.TEST_NAME"
        CASE_ALL = "$params.ALL_TEST"
        SOURCE_URL = "$params.URL"
        SOURCE_BRANCH = "$params.BRANCH"
        SOURCE_MANIFEST = "$params.MANIFEST"
        SOURCE_GROUPS = "$params.GROUPS"
        YAML_CONFIG = "$params.YAML_CONFIG"
        NEXUS_URL = "$params.NEXUS_URL"

        SRC_HOME = "${WORKSPACE}/${SOURCE_BRANCH}/src/${BUILD_NUMBER}"
        CLEAN_HOME = "${WORKSPACE}/${SOURCE_BRANCH}/src"
        SOURCE_DIR = "${SRC_HOME}/workspace-test"
        SCRIPT_PATH = "${SRC_HOME}/AATM"
        TEST_LOG_PATH = "${SRC_HOME}/AATM/utilities/"
    }
    stages{
        stage('Prepare') {
            steps {
                script {
                    echo("Cleanup workspace ${CLEAN_HOME}")
                    try {
                        sh("sudo rm -rf '${CLEAN_HOME}' ")
                    } catch (err) {
                    }
                }
            }
        }
        stage('jobRun'){
            steps{
                dir(WORKSPACE){
                    sh("""ls -al""")
                    sh("""mkdir -p '${SRC_HOME}'""")
                    sh("""cp -r ./release_build_clean/AATM ${SRC_HOME} """)
                }
                dir(SCRIPT_PATH){
                    script {
                        catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                            echo 'This is jobRun step'
                            echo "${params.TEST_INDEX}"
                            echo "${params.TEST_NAME}"
                            echo "${params.ALL_TEST}"
                            if ("${params.TEST_INDEX}" == "none" && "${params.TEST_NAME}" == "none" && "${params.ALL_TEST}" == '-a') {
                                sh  '''
                                    /bin/python3 run_test.py \
                                    -d ${SOURCE_DIR} \
                                    -a \
                                    -u ${SOURCE_URL} \
                                    -b ${SOURCE_BRANCH} \
                                    -m ${SOURCE_MANIFEST} \
                                    -g ${SOURCE_GROUPS} \
                                    -c ${YAML_CONFIG} \
                                    -x ${NEXUS_URL}
                                '''
                            } else if ("${params.TEST_INDEX}" == "none" && "${params.TEST_NAME}" != "none" && "${params.ALL_TEST}" != '-a') {
                                sh '''
                                    /bin/python3 run_test.py \
                                    -n ${CASE_NAME} \
                                    -d ${SOURCE_DIR} \
                                    -u ${SOURCE_URL} \
                                    -b ${SOURCE_BRANCH} \
                                    -m ${SOURCE_MANIFEST} \
                                    -g ${SOURCE_GROUPS} \
                                    -c ${YAML_CONFIG} \
                                    -x ${NEXUS_URL}
                                '''
                            } else if ("${params.TEST_INDEX}" != "none" && "${params.TEST_NAME}" == "none" && "${params.ALL_TEST}" != '-a') {
                                sh '''
                                    /bin/python3 run_test.py \
                                     ${CASE_INDEX} \
                                    -d ${SOURCE_DIR} \
                                    -u ${SOURCE_URL} \
                                    -b ${SOURCE_BRANCH} \
                                    -m ${SOURCE_MANIFEST} \
                                    -g ${SOURCE_GROUPS} \
                                    -c ${YAML_CONFIG} \
                                    -x ${NEXUS_URL}
                                '''
                            }
                        }
                    }
                }
            }
        }
        stage('Archive'){
            steps{
                echo("scan log")
                dir(TEST_LOG_PATH){
                    script {
                        catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                            sh """
                                ls -al && pwd && ls -al ./cix_run_test_log
                            """
                            sh """
                                cp ./cix_run_test_log/result_record.log . && cp ./cix_run_test_log/current_manifest.xml . && cp ./cix_run_test_log/*.html .
                            """
                            echo "tar -zcvf ${formattedDate}-cix_run_test_log.tar.gz cix_run_test_log"
                            sh """
                                tar -zcvf ${formattedDate}-cix_run_test_log.tar.gz cix_run_test_log
                            """
                        }
                        archiveArtifacts artifacts: "*.gz, result_record.log, current_manifest.xml, *.html", followSymlinks: false
                    }
                }
            }
        }
    }
    post {
        always {
            script {
                SendCiMail(env.JOB_NAME,env.BUILD_NUMBER,env.BUILD_URL)
            }
        }
    }
}