#!/bin/groovy
/*
 * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The OpenAirInterface Software Alliance licenses this file to You under
 * the OAI Public License, Version 1.1  (the "License"); you may not use this file
 * except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.openairinterface.org/?page_id=698
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *-------------------------------------------------------------------------------
 * For more information about the OpenAirInterface (OAI) Software Alliance:
 *      contact@openairinterface.org
 */


// Location of the test XML file to be run
def testXMLFile = params.pythonTestXmlFile
def mainPythonAllXmlFiles = ""
def buildStageStatus = true

// Global Parameters.
def eNB_Repository
def eNB_Branch
def eNB_CommitID
def eNB_AllowMergeRequestProcess = false
def eNB_TargetBranch

pipeline {
    agent {
        label pythonExecutor 
    }
    options {
        disableConcurrentBuilds()
	timestamps()
        ansiColor('xterm')
    }
    stages {
        stage ('Retrieve latest from branch') {
            steps {
                script {
                    checkout([$class: 'GitSCM', branches: [[name: '*/gNB-nrUE-USRP']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'https://gitlab.eurecom.fr/oai/openairinterface5g.git']]])
                    sh "git clean -x -d -ff"
                    sh "git log -n1"
                }
            }
        }
        stage ("Print latest commit info") {
            steps {
                echo "Building on: "
                echo "  Repository -- ${GIT_URL}"
                echo "  Branch -- ${GIT_BRANCH}"
                echo "  Commit -- ${GIT_COMMIT}"
                sh "git log -n1"
            }
        }
        stage ("Verify Parameters") {
            steps {
                script {
                    echo '\u2705 \u001B[32mVerify Parameters\u001B[0m'
                    def allParametersPresent = true

                    // It is already too late to check it
                    if (params.pythonExecutor != null) {
                       echo "eNB CI executor node  :   ${pythonExecutor}"
                    }
                    // If not present picking a default XML file
                    if (params.pythonTestXmlFile == null) {
                        // picking default
                        testXMLFile = 'xml_files/gnb_usrp_build.xml'
                        echo "Test XML file(default):   ${testXMLFile}"
                        mainPythonAllXmlFiles += "--XMLTestFile=" + testXMLFile + " "
                    } else {
                        String[] myXmlTestSuite = testXMLFile.split("\\r?\\n")
                        for (xmlFile in myXmlTestSuite) {
                            if (fileExists("ci-scripts/" + xmlFile)) {
                                mainPythonAllXmlFiles += "--XMLTestFile=" + xmlFile + " "
                                echo "Test XML file         :   ${xmlFile}"
                            }
                        }
                    }
                    // If not present picking a default Stage Name
                    if (params.pipelineTestStageName == null) {
                        // picking default
                        testStageName = 'Template Test Stage'
                    }
                    echo "params.eNB_IPAddress = ${params.eNB_IPAddress}"
                    if (params.eNB_IPAddress == null) {
                        allParametersPresent = false
                    }
                    echo "params.UE_IPAddress = ${params.UE_IPAddress}"
                    if (params.UE_IPAddress == null) {
                        allParametersPresent = false
                    }
                    echo "params.eNB_SourceCodePath = ${params.eNB_SourceCodePath}"
                    if (params.eNB_SourceCodePath == null) {
                        allParametersPresent = false
                    }
                    echo "params.eNB_Credentials = ${params.eNB_Credentials}"
                    if (params.eNB_Credentials == null) {
                        allParametersPresent = false
                    }
                    echo "params.UE_Credentials = ${params.UE_Credentials}"
                    if (params.UE_Credentials == null) {
                        allParametersPresent = false
                    }
                    echo "params.eNB_Repository = ${params.eNB_Repository}"
                    if (params.eNB_Repository == null) {
                        eNB_Repository = env.GIT_URL
                    } else {
                        eNB_Repository = params.eNB_Repository
                    }
                    if (allParametersPresent) {
                        echo "All parameters are present"
                        sh "git fetch"
                        sh "git checkout -f ${eNB_CommitID}"
                    } else {
                        echo "Some parameters are missing"
                        sh "./ci-scripts/fail.sh"
                    }
                }
            }
        }

        stage ("Build and Test") {
            steps {
                script {
                    dir ('ci-scripts') {
                        echo "\u2705 \u001B[32m${testStageName}\u001B[0m"
                        withCredentials([
                            [$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.eNB_Credentials}", usernameVariable: 'eNB_Username', passwordVariable: 'eNB_Password'],
                            [$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.UE_Credentials}", usernameVariable: 'UE_Username', passwordVariable: 'UE_Password']
                        ]) {
                            sh "python3 main.py --mode=InitiateHtml --eNBRepository=${eNB_Repository} --eNBBranch=${eNB_Branch} --eNBCommitID=${eNB_CommitID} --eNB_AllowMerge=${eNB_AllowMergeRequestProcess} --eNBTargetBranch=${eNB_TargetBranch} --ADBIPAddress=${params.ADB_IPAddress} --ADBUserName=${ADB_Username} --ADBPassword=${ADB_Password} --eNBIPAddress=127.0.0.1 --eNBUserName=carabe --eNBPassword=${eNB_Password} ${mainPythonAllXmlFiles}"
                            String[] myXmlTestSuite = testXMLFile.split("\\r?\\n")
                            for (xmlFile in myXmlTestSuite) {
                            if (fileExists(xmlFile)) {
                                try {
                                    sh "python3 main.py --mode=TesteNB --eNBIPAddress=${params.eNB_IPAddress} --eNBRepository=${eNB_Repository} --eNBBranch=${eNB_Branch} --eNBCommitID=${eNB_CommitID} --eNB_AllowMerge=${eNB_AllowMergeRequestProcess} --eNBTargetBranch=${eNB_TargetBranch} --eNBUserName=${eNB_Username} --eNBPassword=${eNB_Password} --eNBSourceCodePath=${params.eNB_SourceCodePath} --EPCIPAddress=${params.EPC_IPAddress} --EPCType=${params.EPC_Type} --EPCUserName=${EPC_Username} --EPCPassword=${EPC_Password} --EPCSourceCodePath=${params.EPC_SourceCodePath} --ADBIPAddress=${params.ADB_IPAddress} --ADBUserName=${ADB_Username} --ADBPassword=${ADB_Password} --XMLTestFile=${xmlFile}"
                                } catch (Exception e) {
                                    currentBuild.result = 'FAILURE'
                                    buildStageStatus = false
                                }
                            }
                            }
                            sh "python3 main.py --mode=FinalizeHtml --finalStatus=${buildStageStatus} --eNBIPAddress=${params.eNB_IPAddress} --eNBUserName=${eNB_Username} --eNBPassword=${eNB_Password}"
                        }
                    }
                }
            }
        }

        stage ("Terminate") {
            parallel {
                stage('Terminate NR UE') {
                    steps {
                        echo '\u2705 \u001B[32mTerminate UE\u001B[0m'
                    }
                    post {
                        success {
                            script {
                                termStatusArray[termUE] = true
                            }
                        }
                    }
                }
                stage('Terminate NR eNB') {
                    steps {
                        echo '\u2705 \u001B[32mTerminate eNB\u001B[0m'
                    }
                    post {
                        success {
                            script {
                                termStatusArray[termENB] = true
                            }
                        }
                    }
                }
            }
        }
    }
}