#!/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
 */

// Abstraction function to send social media messages:
// like on Slack or Mattermost
def sendSocialMediaMessage(pipeChannel, pipeColor, pipeMessage) {
    if (params.pipelineUsesSlack != null) {
        if (params.pipelineUsesSlack) {
            slackSend channel: pipeChannel, color: pipeColor, message: pipeMessage
        }
    }
}

def doRedHatBuild = false
def FDD_Band7_B210_Status

pipeline {
    agent {
        label 'bellatrix'
    }
    options {
        disableConcurrentBuilds()
        timestamps()
        gitLabConnection('OAI GitLab')
        gitlabBuilds(builds: ["Build eNb-USRP", "Build gNb-usrp", "Build nr-UE-usrp", "Build phy-sim", "Analysis with cppcheck"])
        ansiColor('xterm')
    }

    stages {
        stage ("Verify Parameters") {
            steps {
                script {
                    echo '\u2705 \u001B[32mVerify Parameters\u001B[0m'
                    def allParametersPresent = true

                    if (params.RedHatRemoteServer == null) {
                        allParametersPresent = false
                    }
                    if (params.RedHatRemoteCredentials == null) {
                        allParametersPresent = false
                    }
                    if (params.RedHatWorkingPath == null) {
                        allParametersPresent = false
                    }
                    if (allParametersPresent) {
			echo "Performing Red Hat Build"
                        doRedHatBuild = true
                    } else {
                        doRedHatBuild = false
                    }
                }
            }
        }
        stage ("Verify Guidelines") {
            steps {
                echo "Git URL         is ${GIT_URL}"
                echo "GitLab Act      is ${env.gitlabActionType}"
                script {
                    if ("MERGE".equals(env.gitlabActionType)) {
                        // GitLab-Jenkins plugin integration is lacking to perform the merge by itself
                        // Doing it manually --> it may have merge conflicts
                        sh "./ci-scripts/doGitLabMerge.sh --src-branch ${env.gitlabSourceBranch} --src-commit ${env.gitlabMergeRequestLastCommit} --target-branch ${env.gitlabTargetBranch} --target-commit ${GIT_COMMIT}"
                        sh "zip -r -qq localZip.zip ."

                        // Running astyle options on the list of modified files by the merge request
                        // For the moment, there is no fail criteria. Just a notification of number of files that do not follow
                        sh "./ci-scripts/checkCodingFormattingRules.sh --src-branch ${env.gitlabSourceBranch} --target-branch ${env.gitlabTargetBranch}"
                        def res=readFile('./oai_rules_result.txt').trim();
                        if ("0".equals(res)) {
                            def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): All Changed files in Merge Request follow OAI Formatting Rules"
                            addGitLabMRComment comment: message
                        } else {
                            def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): Some Changed files in Merge Request DO NOT follow OAI Formatting Rules"
                            addGitLabMRComment comment: message
                        }
                    } else {
                        echo "Git Branch      is ${GIT_BRANCH}"
                        echo "Git Commit      is ${GIT_COMMIT}"

                        sh "zip -r -qq localZip.zip ."
                        // Running astyle options on all C/H files in the repository
                        // For the moment, there is no fail criteria. Just a notification of number of files that do not follow
                        sh "./ci-scripts/checkCodingFormattingRules.sh"
                    }
                }
            }
            post {
                failure {
                    script {
                        def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): Merge Conflicts -- Cannot perform CI"
                        addGitLabMRComment comment: message
                    }
                }
            }
        }

        stage ("Start VM -- cppcheck") {
            steps {
                sh "./ci-scripts/createVM.sh --variant cppcheck --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }

        stage ("Start VM -- enb-usrp") {
            steps {
                sh "./ci-scripts/createVM.sh --variant enb-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }

        stage ("Start VM -- phy-sim") {
            steps {
                sh "./ci-scripts/createVM.sh --variant phy-sim --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }

        stage ("Start VM -- gnb-usrp") {
            steps {
                sh "./ci-scripts/createVM.sh --variant gnb-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }

        stage ("Start VM -- nu-ue-usrp") {
            steps {
                sh "./ci-scripts/createVM.sh --variant nu-ue-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }

        stage ("Variant Builds") {
            parallel {
                stage ("Analysis with cppcheck") {
                    steps {
                        gitlabCommitStatus(name: "Analysis with cppcheck") {
                            sh "./ci-scripts/buildOnVM.sh --workspace $WORKSPACE --variant cppcheck --job-name ${JOB_NAME} --build-id ${BUILD_ID} --keep-vm-alive"
                        }
                    }
                }
                stage ("Build eNb-USRP") {
                    steps {
                        gitlabCommitStatus(name: "Build eNb-USRP") {
                            sh "./ci-scripts/buildOnVM.sh --workspace $WORKSPACE --variant enb-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID} --keep-vm-alive"
                        }
                    }
                }
                stage ("Build 5G gNB-USRP") {
                    steps {
                        gitlabCommitStatus(name: "Build gNb-usrp") {
                            sh "./ci-scripts/buildOnVM.sh --workspace $WORKSPACE --variant gnb-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID} --keep-vm-alive"
                        }
                    }
                }
                stage ("Build 5G NR-UE-USRP") {
                    steps {
                        gitlabCommitStatus(name: "Build nr-UE-usrp") {
                            sh "./ci-scripts/buildOnVM.sh --workspace $WORKSPACE --variant nu-ue-usrp --job-name ${JOB_NAME} --build-id ${BUILD_ID} --keep-vm-alive"
                        }
                    }
                }
                stage ("Build physical simulators") {
                    steps {
                        gitlabCommitStatus(name: "Build phy-sim") {
                            sh "./ci-scripts/buildOnVM.sh --workspace $WORKSPACE --variant phy-sim --job-name ${JOB_NAME} --build-id ${BUILD_ID} --keep-vm-alive"
                        }
                    }
                }
                stage ("Build eNb-USRP on Red Hat") {
                    when {
                        expression {doRedHatBuild}
                    }
                    steps {
                        gitlabCommitStatus(name: "Build eNb-USRP-CentOS") {
                            script {
                                try {
                                    withCredentials([
                                        [$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.RedHatRemoteCredentials}", usernameVariable: 'RH_Username', passwordVariable: 'RH_Password']
                                    ]) {
                                        sh "./ci-scripts/buildOnRH.sh --workspace $WORKSPACE --job-name ${JOB_NAME} --build-id ${BUILD_ID} --remote-host ${params.RedHatRemoteServer} --remote-path ${params.RedHatWorkingPath} --remote-user-name ${RH_Username} --remote-password ${RH_Password}"
                                    }
                                } catch (Exception e) {
                                    echo "Red Hat build failed not an error now"
                                }
                            }
                        }
                    }
                }
            }
            post {
                always {
                    script {
                        dir ('archives') {
                            sh "zip -r -qq vm_build_logs.zip enb_usrp phy_sim cppcheck gnb_usrp nrue_usrp red_hat"
                        }
                        if(fileExists('archives/vm_build_logs.zip')) {
                            archiveArtifacts artifacts: 'archives/vm_build_logs.zip'
                        }
                        if ("MERGE".equals(env.gitlabActionType)) {
                            sh "./ci-scripts/reportBuildLocally.sh --git-url ${GIT_URL} --job-name ${JOB_NAME} --build-id ${BUILD_ID} --trigger merge-request --src-branch ${env.gitlabSourceBranch} --src-commit ${env.gitlabMergeRequestLastCommit} --target-branch ${env.gitlabTargetBranch} --target-commit ${GIT_COMMIT}"
                            sh "./ci-scripts/checkAddedWarnings.sh --src-branch ${env.gitlabSourceBranch} --target-branch ${env.gitlabTargetBranch}"
                            def res=readFile('./oai_warning_files.txt').trim();
                            if ("0".equals(res)) {
                                echo "No issues w/ warnings/errors in this merge request"
                            } else {
                                def fileList=readFile('./oai_warning_files_list.txt').trim();
                                def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): Some modified files in Merge Request MAY have INTRODUCED WARNINGS (" + fileList + ")"
                                addGitLabMRComment comment: message
                            }
                        } else {
                            sh "./ci-scripts/reportBuildLocally.sh --git-url ${GIT_URL} --job-name ${JOB_NAME} --build-id ${BUILD_ID} --trigger push --branch ${GIT_BRANCH} --commit ${GIT_COMMIT}"
                        }
                        if(fileExists('build_results.html')) {
                            archiveArtifacts artifacts: 'build_results.html'
                        }
                    }
                }
            }
        }

        stage ("Destroy all Virtual Machines") {
            steps {
                sh "./ci-scripts/destroyAllRunningVM.sh --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }
    }
    post {
        always {
            script {
                // Stage destroy may not be run if error in previous stage
                sh "./ci-scripts/destroyAllRunningVM.sh --job-name ${JOB_NAME} --build-id ${BUILD_ID}"
            }
        }
        success {
            script {
                def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): passed (" + BUILD_URL + ")"
                if ("MERGE".equals(env.gitlabActionType)) {
                    echo "This is a MERGE event"
                    addGitLabMRComment comment: message
                    def message2 = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): passed (" + BUILD_URL + ") -- MergeRequest #" + env.gitlabMergeRequestIid + " (" + env.gitlabMergeRequestTitle + ")"
                    sendSocialMediaMessage('ci-enb', 'good', message2)
                } else {
                    sendSocialMediaMessage('ci-enb', 'good', message)
                }
            }
        }
        failure {
            script {
                def message = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): failed (" + BUILD_URL + ")"
                if ("MERGE".equals(env.gitlabActionType)) {
                    echo "This is a MERGE event"
                    addGitLabMRComment comment: message
                    def message2 = "OAI " + JOB_NAME + " build (" + BUILD_ID + "): failed (" + BUILD_URL + ") -- MergeRequest #" + env.gitlabMergeRequestIid + " (" + env.gitlabMergeRequestTitle + ")"
                    sendSocialMediaMessage('ci-enb', 'danger', message2)
                } else {
                    sendSocialMediaMessage('ci-enb', 'danger', message)
                }
            }
        }
    }
}