pipeline {
    agent { label "osx && arm64" }

    environment {
        BUILD_OPTIONS = ''
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '135', daysToKeepStr: '21'))
        gitLabConnection('GitLabConnectionJenkins')
    }

    stages {
        stage('clean previous runs and update gitlab commit status'){
            steps{
                deleteDir()
                updateGitlabCommitStatus(name: 'Build macos', state: 'running')
            }
        }

        stage('Get build parameters'){
            parallel{
                stage('Get build options'){
                    when {
                        allOf {
                            expression { env.gitlabTriggerPhrase != null }
                            expression { env.gitlabTriggerPhrase.contains('BUILD_OPTIONS') }
                        }
                    }
                    steps {
                        script{
                            env.BUILD_OPTIONS = sh(script: 'echo "$gitlabTriggerPhrase" | grep BUILD_OPTIONS | awk -F "BUILD_OPTIONS="  \'{print \$2}\' | cut -d"\"" -f2', returnStdout: true).trim()
                            println BUILD_OPTIONS
                        }
                    }
                    post{
                        always {
                            script{
                                if (currentBuild.currentResult == 'FAILURE'){
                                    addGitLabMRComment(comment: ":red_circle: ${env.JOB_NAME} FAILURE when getting the additional build parameters :worried:<br/>Build results: [Jenkins [${env.JOB_NAME} ${env.BUILD_DISPLAY_NAME}]](${env.RUN_DISPLAY_URL})<br/>Commit: ${env.GIT_COMMIT}" )
                                }
                            }
                        }
                    }
                }

                stage('Get SDK branch'){
                    steps {
                        script{
                            env.SDK_BRANCH = sh(script: 'echo "$gitlabMergeRequestDescription" | grep SDK_SUBMODULE_TEST | awk -F "SDK_SUBMODULE_TEST="  \'{print \$2}\' | cut -d" " -f1', returnStdout: true).trim()
                            if (SDK_BRANCH == ""){
                                echo "SDK_BRANCH was not found on description so develop will be used by default"
                                env.SDK_BRANCH = "develop"
                            }
                            println SDK_BRANCH
                        }
                    }
                    post{
                        always {
                            script{
                                if (currentBuild.currentResult == 'FAILURE'){
                                    addGitLabMRComment(comment: ":red_circle: ${env.JOB_NAME} FAILURE when getting the SDK branch :worried:<br/>Build results: [Jenkins [${env.JOB_NAME} ${env.BUILD_DISPLAY_NAME}]](${env.RUN_DISPLAY_URL})<br/>Commit: ${env.GIT_COMMIT}" )
                                }
                            }
                        }
                    }
                }
            }
        }
        stage('Checkout sources'){
            parallel{
                stage('Checkout MEGAcmd with prebuildmerge'){
                    steps{
                        checkout([
                            $class: 'GitSCM',
                            branches: [[name: "origin/${env.gitlabSourceBranch}"]],
                            userRemoteConfigs: [[ url: "${env.GIT_URL_MEGACMD}", credentialsId: "12492eb8-0278-4402-98f0-4412abfb65c1" ]],
                            extensions: [
                                [$class: "UserIdentity",name: "jenkins", email: "jenkins@jenkins"],
                                [$class: 'PreBuildMerge', options: [fastForwardMode: 'FF', mergeRemote: "origin", mergeStrategy: 'DEFAULT', mergeTarget: "${env.gitlabTargetBranch}"]]
                            ]
                        ])
                    }
                }
                stage('Checkout SDK'){
                    steps{
                        dir('sdk'){
                            checkout([
                                $class: 'GitSCM',
                                branches: [[name: "origin/${SDK_BRANCH}"]],
                                userRemoteConfigs: [[ url: "${env.GIT_URL_SDK}", credentialsId: "12492eb8-0278-4402-98f0-4412abfb65c1" ]],
                                extensions: [
                                    [$class: "UserIdentity",name: "jenkins", email: "jenkins@jenkins"],
                                    [$class: "CloneOption", depth: 1, shallow: true, noTags: false, reference: '']
                                ]
                            ])
                        }
                        script{
                            mac_sources_workspace = WORKSPACE
                        }
                    }
                }
            }
        }

        stage('Build MEGAcmd'){
            environment{
                PATH = "/usr/local/bin:${env.PATH}"
                VCPKGPATH = "${env.HOME}/jenkins/3rdparty"
                BUILD_DIR = "build/cmake/build_dir"
            }
            options{
                timeout(time: 3, unit: 'HOURS')
            }
            steps{
                sh '''sed -i '' 's/-2_3/-2_5/g' sdk/contrib/cmake/CMakeLists.txt'''
                sh "rm -rf ${BUILD_DIR}; mkdir ${BUILD_DIR}"
                sh "cmake -DCMAKE_VERBOSE_MAKEFILE=1 -DENABLE_MEGACMD_TESTS=1 -DCMAKE_BUILD_TYPE=Debug -DUSE_PREBUILT_3RDPARTY=0 -DUSE_THIRDPARTY_FROM_VCPKG=1 -DMega3rdPartyDir='${VCPKGPATH}' '${env.BUILD_OPTIONS}' -S '${mac_sources_workspace}'/build/cmake/ -B '${mac_sources_workspace}'/build/cmake/build_dir/"
                sh "cmake --build ${mac_sources_workspace}/${BUILD_DIR} --target mega-cmd-server -j 1"
                sh "cmake --build ${mac_sources_workspace}/${BUILD_DIR} --target mega-cmd -j 1"
                sh "cmake --build ${mac_sources_workspace}/${BUILD_DIR} --target mega-exec -j 1"
                sh "cmake --build ${mac_sources_workspace}/${BUILD_DIR} --target mega-cmd-tests-unit -j 1"
                sh "cmake --build ${mac_sources_workspace}/${BUILD_DIR} --target mega-cmd-tests-integration -j 1"
            }
        }

        stage('Run unit tests'){
            options{
                timeout(time: 5, unit: 'MINUTES')
            }
            steps{
                dir('test-results') {
                    sh """#!/bin/zsh
                set -x
                export TMP=\$(mktemp -d)
                export HOME=\$TMP
                mkdir -p \$HOME/Library/Caches
                cleanup() {
                    ARG=\$?
                    rm -rf \$TMP
                    exit \$ARG
                }
                trap cleanup EXIT
                ${mac_sources_workspace}/build/cmake/build_dir/mega-cmd-tests-unit --gtest_output=xml:${mac_sources_workspace}/test-results/megacmd-unit-tests.xml --gtest_shuffle
                """
                }
            }
            post {
                always {
                    junit(testResults: "**/test-results/megacmd-unit-tests.xml", keepProperties: true)
                }
            }
        }
        stage('Run integration tests'){
            options {
                timeout(time: 10, unit: 'MINUTES')
            }
            environment{
                MEGACMD_TEST_USER=''
                MEGACMD_TEST_PASS=credentials('MEGACMD_TESTS_PASSWORD')
            }
            steps{
                lock(label: 'testing_accounts_megacmd', variable: 'MEGACMD_TEST_USER', quantity: 1, resource: null){
                    dir('test-results') {
                        sh """#!/bin/zsh
                set -x
                export TMP=\$(mktemp -d)
                export HOME=\$TMP
                export MEGACMD_SOCKET_NAME=cmd.sock
                mkdir -p \$HOME/Library/Caches
                cleanup() {
                    ARG=\$?
                    rm -rf \$TMP
                    exit \$ARG
                }
                trap cleanup EXIT
                ${mac_sources_workspace}/build/cmake/build_dir/mega-cmd-tests-integration --gtest_output=xml:${mac_sources_workspace}/test-results/megacmd-integration-tests.xml --gtest_shuffle
                """
                    }
                }
            }
            post {
                always {
                    junit(testResults: "**/test-results/megacmd-integration-tests.xml", keepProperties: true)
                }
            }
        }
    }

    post{
        always{
            //archiveArtifacts artifacts: 'build_dir/archives_*.tar.gz, build_dir/test_config_folder/logs/*log*', fingerprint: true
            script{
                if (currentBuild.currentResult == 'SUCCESS'){
                    addGitLabMRComment(comment: ":white_check_mark: ${currentBuild.projectName} :green_apple: <b>macOS</b> SUCCEEDED :muscle:<br/>Build results: [Jenkins [${currentBuild.displayName}]](${currentBuild.absoluteUrl})<br/>Commit: ${env.GIT_COMMIT}" )
                    updateGitlabCommitStatus(name: 'Build macos', state: 'success')
                }
                if (currentBuild.currentResult == 'FAILURE'){
                    addGitLabMRComment(comment: ":red_circle: ${currentBuild.projectName} :green_apple: <b>macOS</b> FAILURE  :worried:<br/>Build results: [Jenkins [${currentBuild.displayName}]](${currentBuild.absoluteUrl})<br/>Commit: ${env.GIT_COMMIT}" )
                    updateGitlabCommitStatus(name: 'Build macos', state: 'failed')
                }
                if (currentBuild.currentResult == 'ABORTED'){
                    addGitLabMRComment(comment: ":interrobang: ${currentBuild.projectName} :green_apple: <b>macOS</b> ABORTED  :confused:<br/>Build results: [Jenkins [${currentBuild.displayName}]](${currentBuild.absoluteUrl})<br/>Commit: ${env.GIT_COMMIT}" )
                    updateGitlabCommitStatus(name: 'Build macos', state: 'canceled')
                }
                if (currentBuild.currentResult == 'UNSTABLE'){
                    addGitLabMRComment(comment: ":interrobang: ${currentBuild.projectName} :green_apple: <b>macOS</b> UNSTABLE  :confused:<br/>Build results: [Jenkins [${currentBuild.displayName}]](${currentBuild.absoluteUrl})<br/>Commit: ${env.GIT_COMMIT}" )
                    updateGitlabCommitStatus(name: 'Build macos', state: 'failed')
                }
            }
        }
    }
}
