pipeline {

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

	environment {
		def resolveSucceded = "false"
	}
	
	stages {
    	stage('Resolve') {
    		steps{
    		    sh 'echo Resolve stage'
                //updateGitlabCommitStatus name: 'Resolve', state: 'pending'
                dir('asn_modules') {
                    checkout changelog: true, poll: false, scm: [
                        $class: 'GitSCM', branches: [[name: "${env.gitlabAfter}"]],
                        doGenerateSubmoduleConfigurations: false,
                        extensions: [[$class: 'PreBuildMerge', options: [
                        fastForwardMode: 'FF', mergeRemote: 'origin', mergeStrategy: 'DEFAULT', 
                        mergeTarget: "${env.gitlabTargetBranch}"]]
                        ],
                        submoduleCfg: [],
                        userRemoteConfigs: [[
                        credentialsId: '731ae722-2828-45b8-83f4-ae59fe1cae50', 
                        url: "${env.gitlabSourceRepoSshUrl}" ]]
                    ]
                    sh 'git log --oneline -n 5'
                    sh 'git status -sb'

                }
                dir('scripts'){
                    checkout changelog: false, poll: false, scm: [
                        $class: 'GitSCM', branches: [[name: '*/master']], 
                        doGenerateSubmoduleConfigurations: false, extensions: [], 
                        submoduleCfg: [], userRemoteConfigs: [[
                        credentialsId: '731ae722-2828-45b8-83f4-ae59fe1cae50', 
                        url: 'git@forge.3gpp.org:tools/3gpp-scripts.git']]
                    ]
                }
				//updateGitlabCommitStatus name: 'Resolve', state: 'success'
				script {
					env.resolveSucceded = "true"
				}
            }
		}
		stage('Validate') {
    		steps{
    		    //updateGitlabCommitStatus name: 'Validate', state: 'pending'
    			sh 'echo Validate stage'
    			sh 'bash ./scripts/validate-asn.sh ./asn_modules'
    			//updateGitlabCommitStatus name: 'Validate', state: 'success'
			}
		}
		stage('Deploy to FTP') {
    		steps{
    			sh 'echo DEPLOY stage'
			}
		}
	}
	
    post {
		failure {
			script {
				if (env.resolveSucceded == "false") {
					// updateGitlabCommitStatus name: 'Resolve', state: 'failed'
					sh 'echo Failed'
				}
			}

			
			// updateGitlabCommitStatus name: 'Validate', state: 'failed'
			mail to: 'miguelangel.reinaortega@etsi.org',
				subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
				body: "Something is wrong with ${env.BUILD_URL}"
		}
	}
}
