/**
 * Pipeline to construct a build version of the RAR of JackRabbit JCA customized for Silverpeas.
 *
 * The build is performed within a dedicated Docker image in order to ensure the reproducibility of
 * the builds and to containerize them from the host OS.
 */
pipeline {

  agent {
    docker {
      image 'silverpeas/silverbuild'
      args '''
          -v $HOME/.m2/settings.xml:/home/silverbuild/.m2/settings.xml 
          -v $HOME/.m2/settings-security.xml:/home/silverbuild/.m2/settings-security.xml 
          -v $HOME/.gitconfig:/home/silverbuild/.gitconfig 
          -v $HOME/.ssh:/home/silverbuild/.ssh 
          -v $HOME/.gnupg:/home/silverbuild/.gnupg
          '''
    }
  }

  environment {
    nexusRepo = 'https://nexus3.silverpeas.org/repository/builds'
    gitRepo = 'https://github.com/Silverpeas/Silverpeas-Jackrabbit-JCA'
    gitCredential = 'cacc0467-7c85-41d1-bf4e-eaa470dd5e59'
    buildNumber = (new Date()).format('yyMMdd')
    buildVersion = ''
    release = ''
    jcaVersion = ''
    artifact = 'target/build.yaml'
  }

  stages {
    stage('Prepare') {
      steps {
        echo "Prepare the build ${buildNumber} of Silverpeas Jackrabbit JCA..."
        git([url: gitRepo, credentialsId: gitCredential])
        script {
          def pom = readMavenPom()
          jcaVersion = pom.properties['silverpeas-jca.version']
          release = pom.properties['next.release']
          buildVersion = "${release}-build${buildNumber}"
        }
      }
    }
    stage('Check current version') {
      when {
        expression { jcaVersion.contains('SNAPSHOT') }
      }
      steps {
        error "The Silverpeas JCR AccessControl dependency must be a stable or a build version for this project to be released. Current version is ${jcaVersion}"
      }
    }
    stage('Build and publish') {
      steps {
        script {
          sh """
mvn -U versions:set -DgenerateBackupPoms=false -DnewVersion=${buildVersion}
mvn clean deploy -DaltDeploymentRepository=silverpeas::default::${nexusRepo} -Djava.awt.headless=true
"""
        }
      }
    }
    stage('Create YAML build report') {
      steps {
        script {
          final String commit = sh script: 'git rev-parse HEAD', returnStdout: true
          writeYaml file: artifact, data: ['version': buildVersion,
                                           'commit': commit.trim(),
                                           'release': release]
        }
      }
    }
  }
  post {
    success {
      script {
        currentBuild.displayName = buildVersion
      }
      archiveArtifacts artifacts: artifact, fingerprint: true
    }
    always {
      step([$class                  : 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients              : "miguel.moquillon@silverpeas.org, silveryocha@chastagnier.com",
            sendToIndividuals       : true])
    }
  }
}
