// Copyright 2017-present Open Networking Foundation
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// 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.

node ("${TestNodeName}") {
    timeout (200) {
        try {
            stage ("Parse deployment configuration file") {
                sh returnStdout: true, script: "rm -rf ${configBaseDir}"
                sh returnStdout: true, script: "git clone -b ${branch} ${cordRepoUrl}/${configBaseDir}"
                deployment_config = readYaml file: "${configBaseDir}/${configDeploymentDir}/${configFileName}.yaml"
            }
            stage('Download Test repos') {
                timeout(2) {
                    sh returnStdout: true, script: """
                    rm -rf helm-charts cord-tester voltha voltha-system-tests
                    git clone -b ${branch} ${cordRepoUrl}/helm-charts # NOTE do we need helm-charts?
                    git clone -b ${branch} ${cordRepoUrl}/cord-tester
                    git clone -b ${branch} ${cordRepoUrl}/voltha-system-tests
                    git clone -b ${branch} ${cordRepoUrl}/voltha # NOTE do we need the voltha source code??
                    """
                }
            }
            stage('Subscriber Validation and Ping Tests') {
                timeout(180) {
                    sh """
                    export KUBECONFIG=$WORKSPACE/${configBaseDir}/${configKubernetesDir}/${configFileName}.conf
                    cd $WORKSPACE
                    rm -rf *.log
                    export VOLTCONFIG=/home/cord/.volt/config ; sleep 10
                    cd $WORKSPACE/voltha-system-tests
                    make vst_venv
                    source vst_venv/bin/activate
                    cd tests
                    robot --removekeywords wuks -i sanity -i functional -e bbsim -e notready -d Log -V $WORKSPACE/${configBaseDir}/${configDeploymentDir}/${configFileName}.yaml -v POD_NAME:${configFileName} -v KUBERNETES_CONFIGS_DIR:$WORKSPACE/${configBaseDir}/${configKubernetesDir} functional/Voltha_PODTests.robot || true
                    //robot --removekeywords wuks -i PowerSwitch -i functional -e bbsim -e notready -d Log -T -V $WORKSPACE/${configBaseDir}/${configDeploymentDir}/${configFileName}.yaml -v POD_NAME:${configFileName} -v KUBERNETES_CONFIGS_DIR:$WORKSPACE/${configBaseDir}/${configKubernetesDir} functional/Voltha_FailureScenarios.robot || true                    
                    //robot --removekeywords wuks -i functional -e bbsim -e notready -d Log -T -V $WORKSPACE/${configBaseDir}/${configDeploymentDir}/${configFileName}.yaml -v POD_NAME:${configFileName} -v KUBERNETES_CONFIGS_DIR:$WORKSPACE/${configBaseDir}/${configKubernetesDir} functional/Voltha_ErrorScenarios.robot || true                    
                    kubectl get pods --all-namespaces -o jsonpath="{range .items[*].status.containerStatuses[*]}{.image}{'\\t'}{.image}{'\\n'}" | sort | uniq
                    kubectl get pods --all-namespaces -o jsonpath="{range .items[*].status.containerStatuses[*]}{.image}{'\\t'}{.imageID}{'\\n'}" | sort | uniq
                    kubectl get nodes -o wide
                    kubectl get pods -n voltha -o wide
                    """
                }
            }
            stage('Publish test results') {
                sh returnStdout: true, script: """
                if [ -d RobotLogs ]; then rm -r RobotLogs; fi; mkdir RobotLogs;
                mkdir RobotLogs/TestDoc || true
                cp -r $WORKSPACE/voltha-system-tests/tests/Log/* $WORKSPACE/RobotLogs || true
                export KUBECONFIG=$WORKSPACE/${configBaseDir}/${configKubernetesDir}/${configFileName}.conf
                ## get default pod logs
                for pod in \$(kubectl get pods --no-headers | awk '{print \$1}');
                do
                  kubectl logs \$pod> $WORKSPACE/\$pod.log;
                done
                ## get voltha pod logs
                for pod in \$(kubectl get pods --no-headers -n voltha | awk '{print \$1}');
                do
                  if [[ \$pod == *"-api-"* ]]; then
                    kubectl logs \$pod arouter -n voltha > $WORKSPACE/\$pod.log;
                  else
                    kubectl logs \$pod -n voltha > $WORKSPACE/\$pod.log;
                  fi
                done
                """
                step([$class: 'RobotPublisher',
                    disableArchiveOutput: false,
                    logFileName: 'RobotLogs/log*.html',
                    otherFiles: '',
                    outputFileName: 'RobotLogs/output*.xml',
                    outputPath: '.',
                    passThreshold: 100,
                    reportFileName: 'RobotLogs/report*.html',
                    unstableThreshold: 0
                ]);
                archiveArtifacts artifacts: '*.log'
            }
            currentBuild.result = 'SUCCESS'
        } catch (err) {
            currentBuild.result = 'FAILURE'
            step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "${notificationEmail}", sendToIndividuals: false])
        }
        echo "RESULT: ${currentBuild.result}"
    }
}
