import java.util.regex.Matcher

/**
 * Pipeline to construct a build version of the Web Browser Edition library for Silverpeas. The
 * execution of the pipeline depends on the latest successful build version of Silverpeas as it
 * fetches the build result report from the successful Jenkins job in order to update correctly its
 * dependencies on both Silverpeas Core. As the version lifecycle of the project can differ from the
 * Silverpeas one, this pipeline releases a version timestamped with the date of the build;
 * meaning this build version can be as well as the same of the latest one of Silverpeas than it can
 * be different.
 *
 * This pipeline expects the following environment variables to be set:
 * STABLE_BRANCH     the SCM branch in which the current stable version of the project is currently
 *                   maintained
 * IMAGE_FOR_STABLE  the version of the Docker image to be used by this pipeline for stable version
 *                   of the project.
 *
 * It requires the following parameters:
 * BRANCH            the branch of the project on which the build version has to be built
 */

String imageVersion = '6.4'

pipeline {

  agent {
    docker {
      image "silverpeas/silverbuild:${imageVersion}"
      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 branch on which the build has to be done',
            name: 'BRANCH',
            defaultValue: 'main'
    )
  }

  environment {
    nexusRepo = 'https://nexus3.silverpeas.org/repository/builds'
    gitRepo = 'https://github.com/Silverpeas/Silverpeas-WebBrowserEdition'
    gitCredential = 'cacc0467-7c85-41d1-bf4e-eaa470dd5e59'
    silverpeasBuildJobName = 'Silverpeas_Stable_AutoDeploy'
    parentVersion = ''
    buildVersion = ''
    release = ''
    silverpeasVersion = ''
    pom = null
    artifact = 'target/build.yaml'
  }

  stages {
    stage('Resolve dependency on Silverpeas') {
      steps {
        script {
          echo "Working on branch ${params.BRANCH}"
          copyArtifacts projectName: silverpeasBuildJobName, flatten: true
          def silverpeasBuild = readYaml file: 'build.yaml'
          parentVersion = silverpeasBuild.parent
          silverpeasVersion = silverpeasBuild.version
          sh 'rm -f build.yaml'
        }
        echo "Parent version is ${parentVersion}"
        echo "Silverpeas version is ${silverpeasVersion}"
      }
    }
    stage('Prepare the project') {
      steps {
        git([url: gitRepo, branch: params.BRANCH, credentialsId: gitCredential])
        script {
          pom = readMavenPom()
          release = pom.properties['next.release']
          buildNumber = (new Date()).format('yyMMdd')
          buildVersion = "${release}-build${buildNumber}"
        }
        echo "Build version will be ${buildVersion}"
      }
    }
    stage('Check POM parent version') {
      when {
        expression { pom.parent.version.contains('SNAPSHOT') }
      }
      steps {
        error "The parent POM must be at a stable or a build version for this project to be deployed. Current version is ${pom.parent.version}"
      }
    }
    stage('Check Silverpeas version') {
      when {
        expression { pom.properties['silverpeas.version'].contains('SNAPSHOT') }
      }
      steps {
        error "The dependency on Silverpeas must be at a stable or at a build version for this project to be deployed. Current version is ${pom.properties['silverpeas.version']}"
      }
    }
    stage('Update POM parent') {
      environment {
        GIT_AUTH = credentials("${gitCredential}")
      }
      when {
        expression {
          !pom.parent.version.matches(/[0-9.]+/) && parentVersion && pom.parent.version != parentVersion
        }
      }
      steps {
        sh '''
          git config --local credential.helper "!f() { echo username=\\${GIT_AUTH_USR}; echo password=\\$GIT_AUTH_PSW; }; f"
          '''
        sh """
          mvn -U versions:update-parent -DgenerateBackupPoms=false -DparentVersion="[${parentVersion}]"
          git commit -am "Update parent POM to version ${parentVersion}"
          git push origin HEAD:${branch}
          """
      }
    }
    stage('Update dependency on Silverpeas') {
      environment {
        GIT_AUTH = credentials("${gitCredential}")
      }
      when {
        expression {
          !pom.properties['silverpeas.version'].matches(/[0-9.]+/) &&
                  pom.properties['silverpeas.version'] != silverpeasVersion
        }
      }
      steps {
        sh '''
          git config --local credential.helper "!f() { echo username=\\${GIT_AUTH_USR}; echo password=\\$GIT_AUTH_PSW; }; f"
          '''
        sh """
          sed -i -e "s/<silverpeas.version>[0-9a-zA-Z.-]\\+/<silverpeas.version>${silverpeasVersion}/g" pom.xml
          git commit -am "Update dependency on Silverpeas to version ${silverpeasVersion}"
          git push origin HEAD:${params.BRANCH}
          """
      }
    }
    stage('Build and Publish') {
      steps {
        sh """
          /opt/wildfly-for-tests/wildfly-*.Final/bin/standalone.sh -c standalone-full.xml &> /dev/null &
          mvn -U versions:set -DgenerateBackupPoms=false -DnewVersion=${buildVersion}
          mvn clean deploy -DaltDeploymentRepository=silverpeas::default::${nexusRepo} -Pdeployment -Pcoverage -Djava.awt.headless=true -Dcontext=ci
          /opt/wildfly-for-tests/wildfly-*.Final/bin/jboss-cli.sh --connect :shutdown
          """
      }
    }
    stage('Create YAML build report') {
      steps {
        script {
          String commit = sh script: 'git rev-parse HEAD', returnStdout: true
          writeYaml file: artifact, data: ['version': buildVersion,
                                           'parent' : parentVersion,
                                           'silverpeas': silverpeasVersion,
                                           'release': release,
                                           'commit' : commit.trim()]
        }
      }
    }
  }
  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])
    }
  }
}