/**
 * Pipeline to release a stable version from given build version of the JCR Access Control library
 * for JackRabbit.
 *
 * In order to get the build version, the pipeline requires the Jenkins job aimed at constructing
 * such build version to be named 'Silverpeas_JCR-AccessController_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-JCR-AccessControl'
    gitCredential = 'cacc0467-7c85-41d1-bf4e-eaa470dd5e59'
    version = ''
    commit = ''
    artifact = 'target/release.yaml'
  }

  stages {
    stage('Prepare the release') {
      steps {
        git([url: gitRepo, credentialsId: gitCredential])
        script {
          copyArtifacts projectName: 'Silverpeas_JCR-AccessController_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}
          """
      }
    }
    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('Prepare the development of the next version') {
      steps {
        environment {
          GIT_AUTH = credentials("${gitCredential}")
        }
        script {
          String[] parts = version.split('\\.')
          String nextVersion = "${parts[0]}.${(parts[1] as int) + 1}"
          echo "Prepare development of ${nextVersion}"
          sh 'git checkout master'
          sh """
            sed -i -e "s/<next.release>[0-9.]\\+/<next.release>${nextVersion}/g" pom.xml
            mvn -U versions:set -DgenerateBackupPoms=false -DnewVersion=${nextVersion}
            mvn clean install -Dmaven.test.skip=true -Prelease-sign-artifacts
            git commit -am "${version} has been released from build ${params.BUILD_VERSION} (${commit}).\\
Prepare for development iteration of next version ${nextVersion}"
            """
          sh '''
            git config --local credential.helper "!f() { echo username=\\${GIT_AUTH_USR}; echo password=\\$GIT_AUTH_PSW; }; f"
            git push origin HEAD:master
            '''
        }
      }
    }
    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])
    }
  }
}
