/**
 * Pipeline to release a stable version from the a given build version of the RAR of JackRabbit
 * JCA customized for Silverpeas.
 *
 * In order to get the build version, the pipeline requires the Jenkins job aimed at constructing
 * such build version to be named 'Silverpeas_Jackrabbit-JCA_AutoDeploy'.
 *
 * This pipeline requires the following parameters:
 * BUILD_VERSION the build version of the project from which the release has to be done.
 *
 * 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
          '''
    }
  }

  parameters {
    string(
        description: 'The build version of the project from which the release has to be done',
        name: 'BUILD_VERSION'
    )
  }

  environment {
    gitRepo = 'https://github.com/Silverpeas/Silverpeas-Jackrabbit-JCA'
    gitCredential = 'cacc0467-7c85-41d1-bf4e-eaa470dd5e59'
    version = ''
    commit = ''
    pom = null
    artifact = 'target/release.yaml'
  }

  stages {
    stage('Prepare the release') {
      steps {
        git([url: gitRepo, credentialsId: gitCredential])
        script {
          copyArtifacts projectName: 'Silverpeas_Jackrabbit-JCA_AutoDeploy',
              flatten: true,
              selector: specific(params.BUILD_VERSION)
          def build = readYaml file: 'build.yaml'
          version = build.release
          commit = build.commit
          sh 'rm -f build.yaml'
        }
      }
    }
    stage("Checkout the build version") {
      steps {
        sh """
          git checkout ${commit}
          git checkout -b release-${version}
          """
        script {
          pom = readMavenPom()
        }
      }
    }
    stage('Check the depencency on the JCR access control library') {
      when {
        expression {
          pom.properties['silverpeas-jca.version'].contains('build') ||
              pom.properties['silverpeas-jca.version'].contains('SNAPSHOT')
        }
      }
      steps {
        error "The Silverpeas JCR AccessControl dependency must be a stable version for " +
            "this project to be released. Current version is ${pom.properties['silverpeas-jca.version']}"
      }
    }
    stage('Release') {
      environment {
        GIT_AUTH = credentials("${gitCredential}")
      }
      steps {
        echo "Release version ${version}"
        sh """
          mvn -U versions:set -DgenerateBackupPoms=false -DnewVersion=${version}
          mvn clean deploy -Dmaven.test.skip=true -Prelease-sign-artifacts
          git commit -am "Release of ${version} from ${params.BUILD_VERSION} (commit ${commit})"
          git tag ${version}
          """
        sh '''
          git config --local credential.helper "!f() { echo username=\\${GIT_AUTH_USR}; echo password=\\$GIT_AUTH_PSW; }; f"
          git push origin --tags
          '''
      }
    }
    stage('Create YAML release report') {
      steps {
        script {
          writeYaml file: artifact, data: ['release': version,
                                           'from'   : ['version': params.BUILD_VERSION,
                                                       'commit' : commit.trim()]]
        }
      }
    }
  }
  post {
    success {
      script {
        currentBuild.displayName = version
      }
      archiveArtifacts artifacts: artifact, fingerprint: true
    }
    always {
      step([$class                  : 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients              : "miguel.moquillon@silverpeas.org, silveryocha@chastagnier.com",
            sendToIndividuals       : true])
    }
  }
}

