pipeline {
    agent { label 'linux' }

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

    environment {
        BUILD_OPTIONS = ' '
        SDK_BRANCH = ' '
    }

    stages {
        stage('Get current build description'){
            steps{
                script{
                    env.currentBuildDescription = currentBuild.description
                }
            }
        }
        stage('get additional build parameters'){
            when {
                allOf {
                    expression { env.gitlabTriggerPhrase != null }
                    expression { env.gitlabTriggerPhrase.contains('BUILD_OPTIONS') }
                }
            }
            steps {
                script{
                    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'){
            when {
                expression { 
                    env.gitlabMergeRequestDescription.contains('SDK_SUBMODULE_TEST')
                }
            }
            steps {
                script{
                    println "${env.gitlabMergeRequestDescription}"
                    env.SDK_BRANCH = sh(script: 'echo "$gitlabMergeRequestDescription" | grep SDK_SUBMODULE_TEST | awk -F "SDK_SUBMODULE_TEST="  \'{print \$2}\' | cut -d" " -f1', returnStdout: true).trim()
                    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('build MEGASync'){
            parallel {
                stage('Build macOS') {
                    when {
                        anyOf {
                            expression { env.gitlabTriggerPhrase != null && ( env.gitlabTriggerPhrase == 'trigger compilation' || env.gitlabTriggerPhrase.startsWith('trigger compilation macos'))  }
                            allOf{
                                expression { env.gitlabTriggerPhrase == null }
                                triggeredBy "GitlabWebhookCause" 
                            }
                        }
                    }
                    steps {
                        gitlabCommitStatus(name: 'MacOS build') {
                            script {
                                echo "Triggering MEGAsync job for macOS."
                                def triggeredBuild = build job: 'MEGASync-MRs-private', wait: true, propagate: false, parameters: [
                                    string(name: 'SOURCE_BRANCH', value: "${env.gitlabSourceBranch}"),
                                    string(name: 'TARGET_BRANCH', value: "${env.gitlabTargetBranch}"),
                                    booleanParam(name: 'BUILD_MAC', value: true),
                                    string(name: 'BUILD_OPTIONS', value: "${BUILD_OPTIONS}"),
                                    string(name: 'BUILD_DESCRIPTION', value: "${env.currentBuildDescription}"),
                                    string(name: 'SDK_BRANCH', value: "${SDK_BRANCH}")
                                    ]
                                env.TRIGGERED_BUILD_URL_MACOS = triggeredBuild.getAbsoluteUrl()
                                env.TRIGGERED_PROJECT_NAME_MACOS = triggeredBuild.getProjectName()
                                env.TRIGGERED_BUILD_DISPLAY_NAME_MACOS = triggeredBuild.getFullDisplayName()
                            }
                        }
                    }
                    post{
                        always {
                            script{
                                if (currentBuild.currentResult == 'SUCCESS'){
                                    addGitLabMRComment(comment: ":white_check_mark: ${env.TRIGGERED_PROJECT_NAME_MACOS} :green_apple: <b>macOS</b> SUCCEEDED :muscle:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_MACOS}]](${env.TRIGGERED_BUILD_URL_MACOS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'MacOS build', state: 'success')
                                }                                
                                if (currentBuild.currentResult == 'FAILURE'){
                                    addGitLabMRComment(comment: ":red_circle: ${env.TRIGGERED_PROJECT_NAME_MACOS} :green_apple: <b>macOS</b> FAILURE  :worried:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_MACOS}]](${env.TRIGGERED_BUILD_URL_MACOS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'MacOS build', state: 'failed')
                                    error "Job failed"
                                }
                                if (currentBuild.currentResult == 'ABORTED'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_MACOS} :green_apple: <b>macOS</b> ABORTED  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_MACOS}]](${env.TRIGGERED_BUILD_URL_MACOS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'MacOS build', state: 'canceled')
                                    error "Job failed"
                                }                                
                                if (currentBuild.currentResult == 'UNSTABLE'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_MACOS} :green_apple: <b>macOS</b> UNSTABLE  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_MACOS}]](${env.TRIGGERED_BUILD_URL_MACOS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'MacOS build', state: 'failed')
                                    error "Job failed"
                                }
                            }

                        }
                    }
                }

                stage('Build Linux') {
                    when {
                        anyOf {
                            expression { env.gitlabTriggerPhrase != null && ( env.gitlabTriggerPhrase == 'trigger compilation' || env.gitlabTriggerPhrase.startsWith('trigger compilation linux'))  }
                            allOf{
                                expression { env.gitlabTriggerPhrase == null }
                                triggeredBy "GitlabWebhookCause" 
                            }
                        }
                    }
                    steps {
                        gitlabCommitStatus(name: 'Linux build') {
                            script {
                                echo "Triggering MEGAsync job for Linux."
                                def triggeredBuild = build job: 'MEGASync-MRs-private', wait: true, propagate: false, parameters: [
                                    string(name: 'SOURCE_BRANCH', value: "${env.gitlabSourceBranch}"),
                                    string(name: 'TARGET_BRANCH', value: "${env.gitlabTargetBranch}"),
                                    booleanParam(name: 'BUILD_LINUX', value: true),
                                    string(name: 'BUILD_OPTIONS', value: "${BUILD_OPTIONS}"),
                                    string(name: 'BUILD_DESCRIPTION', value: "${env.currentBuildDescription}"),
                                    string(name: 'SDK_BRANCH', value: "${SDK_BRANCH}")
                                    ]
                                env.TRIGGERED_BUILD_URL_LINUX = triggeredBuild.getAbsoluteUrl()
                                env.TRIGGERED_PROJECT_NAME_LINUX = triggeredBuild.getProjectName()
                                env.TRIGGERED_BUILD_DISPLAY_NAME_LINUX = triggeredBuild.getFullDisplayName()
                            }
                        }
                    }
                    post{
                        always {
                            script{
                                if (currentBuild.currentResult == 'SUCCESS'){
                                    addGitLabMRComment(comment: ":white_check_mark: ${env.TRIGGERED_PROJECT_NAME_LINUX} :penguin: <b>LINUX</b> SUCCEEDED :muscle:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_LINUX}]](${env.TRIGGERED_BUILD_URL_LINUX})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Linux build', state: 'success')
                                }                                
                                if (currentBuild.currentResult == 'FAILURE'){
                                    addGitLabMRComment(comment: ":red_circle: ${env.TRIGGERED_PROJECT_NAME_LINUX} :penguin: <b>Linux</b> FAILURE  :worried:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_LINUX}]](${env.TRIGGERED_BUILD_URL_LINUX})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Linux build', state: 'failed')
                                    error "Job failed"
                                }
                                if (currentBuild.currentResult == 'ABORTED'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_LINUX} :penguin: <b>Linux</b> ABORTED  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_LINUX}]](${env.TRIGGERED_BUILD_URL_LINUX})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Linux build', state: 'canceled')
                                    error "Job failed"
                                }                                
                                if (currentBuild.currentResult == 'UNSTABLE'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_LINUX} :penguin: <b>Linux</b> UNSTABLE  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_LINUX}]](${env.TRIGGERED_BUILD_URL_LINUX})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Linux build', state: 'failed')
                                    error "Job failed"
                                }
                            }

                        }
                    }
                }

                stage('Build Windows') {
                    when {
                        anyOf {
                            expression { env.gitlabTriggerPhrase != null && ( env.gitlabTriggerPhrase == 'trigger compilation' || env.gitlabTriggerPhrase.startsWith('trigger compilation windows'))  }
                            allOf{
                                expression { env.gitlabTriggerPhrase == null }
                                triggeredBy "GitlabWebhookCause" 
                            }
                        }
                    }
                    steps {
                        gitlabCommitStatus(name: 'Windows build') {
                            script {
                                echo "Triggering MEGAsync job for Windows."
                                def triggeredBuild = build job: 'MEGASync-MRs-private', wait: true, propagate: false, parameters: [
                                    string(name: 'SOURCE_BRANCH', value: "${env.gitlabSourceBranch}"),
                                    string(name: 'TARGET_BRANCH', value: "${env.gitlabTargetBranch}"),
                                    booleanParam(name: 'BUILD_WINDOWS', value: true),
                                    string(name: 'BUILD_OPTIONS', value: "${BUILD_OPTIONS}"),
                                    string(name: 'BUILD_DESCRIPTION', value: "${env.currentBuildDescription}"),
                                    string(name: 'SDK_BRANCH', value: "${SDK_BRANCH}")
                                    ]
                                env.TRIGGERED_BUILD_URL_WINDOWS = triggeredBuild.getAbsoluteUrl()
                                env.TRIGGERED_PROJECT_NAME_WINDOWS = triggeredBuild.getProjectName()
                                env.TRIGGERED_BUILD_DISPLAY_NAME_WINDOWS = triggeredBuild.getFullDisplayName()
                            }
                        }
                    }
                    post{
                        always {
                            script{
                                if (currentBuild.currentResult == 'SUCCESS'){
                                    addGitLabMRComment(comment: ":white_check_mark: ${env.TRIGGERED_PROJECT_NAME_WINDOWS} <b>Windows</b> SUCCEEDED :muscle:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_WINDOWS}]](${env.TRIGGERED_BUILD_URL_WINDOWS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Windows build', state: 'success')
                                }                                
                                if (currentBuild.currentResult == 'FAILURE'){
                                    addGitLabMRComment(comment: ":red_circle: ${env.TRIGGERED_PROJECT_NAME_WINDOWS} <b>Windows</b> FAILURE  :worried:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_WINDOWS}]](${env.TRIGGERED_BUILD_URL_WINDOWS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Windows build', state: 'failed')
                                    error "Job failed"
                                }
                                if (currentBuild.currentResult == 'ABORTED'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_WINDOWS} <b>Windows</b> ABORTED  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_WINDOWS}]](${env.TRIGGERED_BUILD_URL_WINDOWS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Windows build', state: 'canceled')
                                    error "Job failed"
                                }                                
                                if (currentBuild.currentResult == 'UNSTABLE'){
                                    addGitLabMRComment(comment: ":interrobang: ${env.TRIGGERED_PROJECT_NAME_WINDOWS} <b>Windows</b> UNSTABLE  :confused:<br/>Build results: [Jenkins [${env.TRIGGERED_BUILD_DISPLAY_NAME_WINDOWS}]](${env.TRIGGERED_BUILD_URL_WINDOWS})<br/>Commit: ${env.GIT_COMMIT}" )
                                    updateGitlabCommitStatus(name: 'Windows build', state: 'failed')
                                    error "Job failed"
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}