@Library('utils') _

def JIRA_KEY = "RAN"
def POM_PATH = "pom.xml"
def PRINCIPAL_BRANCH = "master"
def BUILD_CMD = "clean install"
def MANUAL = false
def RELEASE_VERSION = ""
def DEV_VERSION
def RELEASE_CMD
def REMOVE_TAG
def VERIF_TAG
def NEW_TAG
def GIT

def AWS_LAMBDA = ""
def DEPLOY_ENV = "gec-integration" //gec-demo ou gec-integration
def CONFIG_ENV = "int" //demo ou int
def ARTIFACTORY = "arondor-snapshot"
def DEPLOY_VERSION

pipeline {
    agent any
    stages {
        stage('Preparation') {
            steps {
                script {
                    env.MAVEN_HOME = tool 'maven3'
					sh "echo ${currentBuild.buildCauses} > build-cause.txt"
                    MANUAL = readFile('build-cause.txt').contains("Started by user")
			        sh "rm -f build-cause.txt"
                    DEPLOY_VERSION = readMavenPom().getVersion()
                }
            }
        }
        stage('Build & Publish') {
            parallel {
                stage('Input') {
                    stages {
                        stage('Release Version') {
                            when {
                                beforeInput true
                                equals expected: "true", actual: "${MANUAL}"
                        		branch "${PRINCIPAL_BRANCH}"
                            }
                            input {
                                message "Do you want to make a release ? "
                                ok "Yes"
                                parameters {
                                    string(name: 'RVERSION', defaultValue: "", description: 'Release version')
                                    string(name: 'DVERSION', defaultValue: "", description: 'Next development version')
                                    string(name: 'BUILD', defaultValue: "${BUILD_CMD}", description: 'Maven build goals')
                                }
                            }
                            steps {
                                script {
					                echo "Release number ${RVERSION} & development number ${DVERSION}"
                                    echo "With maven build goals : ${BUILD}"
                                    RELEASE_VERSION = RVERSION
                                    DEV_VERSION = DVERSION
                                    RELEASE_CMD = BUILD
                                    DEPLOY_VERSION = RELEASE_VERSION
                                    ARTIFACTORY = "arondor-release"
                    				
                    				NEW_TAG = readMavenPom().getArtifactId()
                    				GIT = pipelineUtils.gitPullBranchAndTags("${GIT_URL}", "${BRANCH_NAME}")
                                    NEW_TAG = "release-" + NEW_TAG + "-" + RELEASE_VERSION
                                    VERIF_TAG = pipelineUtils.gitSearchTag(NEW_TAG)
                                }
                            }
                        }
                        stage('Replace Tag') {
                            when {
                                beforeInput true
                                equals expected: "true", actual: "${MANUAL}"
                                equals expected: "true", actual: "${VERIF_TAG}"
                        		branch "${PRINCIPAL_BRANCH}"
                            }
                            input {
                                message "Do you want to replace existing tag release (${NEW_TAG}) ? "
                                ok "Yes"
                            }
                            steps {
                                script {
                                    REMOVE_TAG = true
                                }
                            }    
                        }
                    }
                }
                stage('Build & Publish') {	
                    when {
                        branch "${PRINCIPAL_BRANCH}"
                    }
                    steps {
                        script {
                            pipelineUtils.mavenBuildAndPublish(POM_PATH, BUILD_CMD)
                        }
                    }
                }
                stage('Build') {	
                    when {
                        not { branch "${PRINCIPAL_BRANCH}" }
                    }
                    steps {
                        script {
                            pipelineUtils.mavenBuild(POM_PATH, BUILD_CMD)
                        }
                    }
                }
            }
        }
        stage('Release Git') {
            when {
                equals expected: "true", actual: "${MANUAL}"
				branch "${PRINCIPAL_BRANCH}"
            }
            steps {
                script {
					pipelineUtils.mavenReleaseWithTag(GIT, RELEASE_VERSION, DEV_VERSION, JIRA_KEY, NEW_TAG, POM_PATH, RELEASE_CMD, REMOVE_TAG)
                }
            }
        }
        stage('Release Jira') {
            when {
                equals expected: "true", actual: "${MANUAL}"
				branch "${PRINCIPAL_BRANCH}"
            }
            steps {
                script {
                    pipelineUtils.jiraCreateOrUpdateVersion(JIRA_KEY, RELEASE_VERSION, true)
                    pipelineUtils.jiraIssuesTransition("Livrer", "project = ${JIRA_KEY} AND status = 'Packaging' AND fixVersion = ${RELEASE_VERSION}")
                }
            }
        }
        stage('Deploy Int') { 
            when {
                branch "${PRINCIPAL_BRANCH}"
            }
            steps {
                withAWS(credentials:'sns-aws') {
                    snsPublish(topicArn: AWS_LAMBDA, subject: 'CI Dev build ' + env.BUILD_NUMBER +' ('+ currentBuild.startTimeInMillis +')' , message: 'build ok for ' + env.BUILD_NUMBER, messageAttributes: ['User':ARTIFACTORY_USER, 'Password':ARTIFACTORY_PWD, 'Version':DEPLOY_VERSION, 'Env':DEPLOY_ENV, 'Config':CONFIG_ENV, 'Artifactory':ARTIFACTORY, 'ArtifactPath':readMavenPom().getGroupId().replace(".", "/"), 'ArtifactName':NEW_TAG+"-packaging"])
                }
            }
        }
        stage('Deploy Jira') { 
            when {
                branch "${PRINCIPAL_BRANCH}"
                equals expected: "false", actual: "${MANUAL}"
            }
            steps {
                script {
                    pipelineUtils.jiraIssuesTransition("Phase de recette", "project = ${JIRA_KEY} AND status = 'Recette technique'")
                }
            }
        }
        stage('Deploy Demo') { 
            when {
                branch "${PRINCIPAL_BRANCH}"
                equals expected: "true", actual: "${MANUAL}"
            }
            steps {
                withAWS(credentials:'sns-aws') {
                    snsPublish(topicArn: AWS_LAMBDA, subject: 'CI Dev build ' + env.BUILD_NUMBER +' ('+ currentBuild.startTimeInMillis +')' , message: 'build ok for ' + env.BUILD_NUMBER, messageAttributes: ['User':ARTIFACTORY_USER, 'Password':ARTIFACTORY_PWD, 'Version':DEPLOY_VERSION, 'Env':'gec-demo', 'Config':'demo', 'Artifactory':ARTIFACTORY, 'ArtifactPath':readMavenPom().getGroupId().replace(".", "/"), 'ArtifactName':NEW_TAG+"-packaging"])
                }
            }
        }
    }
    post { 
        always { 
            junit allowEmptyResults: true, testResults:  '**/target/surefire-reports/TEST-*.xml'
            archiveArtifacts artifacts: '**/target/*.jar, **/target/*.zip'
			cleanWs()
        }
    }
}
