pipeline {

    options {
        disableConcurrentBuilds()
        gitLabConnection('Gitlab for 3GPP')
        gitlabBuilds(builds: ["Resolve", "Validate"])
    }
     
    agent any

    stages {
        stage('Resolve') {
            steps{
                sh 'echo Resolve stage'
                script {
                    RESOLVE_SUCCEDED = "false"
                }
                updateGitlabCommitStatus name: 'Resolve', state: 'pending'
                dir('apis') {
                    checkout changelog: true, poll: false, scm: [
                        $class: 'GitSCM', branches: [[name: "${env.gitlabAfter}"]],
                        doGenerateSubmoduleConfigurations: false,
                        submoduleCfg: [],
                        userRemoteConfigs: [[
                        credentialsId: 'Jenkins', 
                        url: "${env.gitlabSourceRepoSshUrl}" ]]
                    ]
                    sh 'git log --oneline -n 5'
                    sh 'git status -sb'
                    //script {
                    //    lastCommit = sh (script: "git rev-parse HEAD", returnStatus: true)
                    //}

                }
                dir('scripts'){
                    checkout changelog: false, poll: false, scm: [
                        $class: 'GitSCM', branches: [[name: '*/master']], 
                        doGenerateSubmoduleConfigurations: false, extensions: [], 
                        submoduleCfg: [], userRemoteConfigs: [[
                        credentialsId: 'Jenkins', 
                        url: 'git@forge.3gpp.org:tools/3gpp-scripts.git']]
                    ]
                }
                updateGitlabCommitStatus name: 'Resolve', state: 'success'
                
                script {
                    RESOLVE_SUCCEDED = "true"
                    //gitlabCommitStatus name: 'Resolve', state: 'success', builds:[[revisionHash:lastCommit]]
                }
                
            }
        }
        stage('Validate') {
            steps{
                updateGitlabCommitStatus name: 'Validate', state: 'pending'
                sh 'echo Validate stage'
                sh 'bash ./scripts/validate-all.sh ./apis'
                updateGitlabCommitStatus name: 'Validate', state: 'success'
                //script {
                //    gitlabCommitStatus name: 'Validate', state: 'success', builds:[[revisionHash:lastCommit]]
                //}
            }
        }
		//stage('Version processing') {
    	//	steps{
    	//	    updateGitlabCommitStatus name: 'Version processing', state: 'pending'
    	//		sh 'echo Version processing stage'
		//		sh 'bash ./scripts/generate-config.sh ./apis'
    	//		updateGitlabCommitStatus name: 'Version processing', state: 'success'
		//	}
		//}
        //stage('Deploy to FTP') {
        //    steps{
        //        sh 'echo DEPLOY stage'
        //    }
        //}
    }
    
    post {

        always {
           		sh 'echo Generating API versions file'
				sh 'bash ./scripts/generate-config.sh ./apis'
                archiveArtifacts artifacts: 'api-versions.txt'
    	}
        
        success {
			script {
                RECIPIENT = """${sh(
                    returnStdout: true,
                    script: "cd apis && git log --format='%ae' HEAD^!"
                )}"""
            }

            echo "Sending email to: ${RECIPIENT}" 
            emailext to: "${RECIPIENT}",
                attachLog: true,
                attachmentsPattern: '**/*.log',
                subject: "[3GPP Forge] Validation succeeded: ${currentBuild.fullDisplayName}",
                body: "Your contribution to 3GPP Forge was applied successfully and, " +
                    "after running the validation process for all the files in the repository, " +
                    "no critical errors were detected.\n" +
                    "Detailed information in the 'Console output' at ${env.BUILD_URL}"
        }

        failure {
            script {
                sh 'printenv'
                if (RESOLVE_SUCCEDED == "false") {
                    updateGitlabCommitStatus name: 'Resolve', state: 'failed'
                    //gitlabCommitStatus name: 'Resolve', state: 'failed', builds:[[revisionHash:lastCommit]]
                    //gitlabCommitStatus name: 'Validate', state: 'failed', builds:[[revisionHash:lastCommit]]
                }
                RECIPIENT = """${sh(
                    returnStdout: true,
                    script: "cd apis && git log --format='%ae' HEAD^!"
                )}"""
            }

            echo "Sending email to: ${RECIPIENT}" 
            emailext to: "${RECIPIENT}",
                attachLog: true,
                attachmentsPattern: '**/*.log',
                subject: "[3GPP Forge] Validation failed: ${currentBuild.fullDisplayName}",
                body: "Your contribution to 3GPP Forge was applied successfully; however, " +
                    "after running the validation process for all the files in the repository, " +
                    "some errors were detected (they may, or may not be related to your own " +
                    "contribution).\nPlease check the 'Console output' at ${env.BUILD_URL}"
            
            updateGitlabCommitStatus name: 'Validate', state: 'failed'
        }
    }
}
