import java.util.regex.Matcher

/**
 * Pipeline to generate and to publish the documentation of a new version of Silverpeas. This
 * pipeline should be triggered once the release of Silverpeas has been successfully performed as it
 * will fetch the release report for additional required information.
 *
 * This pipeline requires the following job 'Silverpeas Project Web Site Publisher' to run the
 * corresponding pipeline in order to publish the Silverpeas community web site.
 *
 * This pipeline requires the following parameters:
 * SILVERPEAS_VERSION   the version of Silverpeas for which the documentation has to be generated
 *                      and published.
 *
 * 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.
 */

String imageVersion = getDockerImageVersion()

def projects = [
    core        : 'Silverpeas-Core',
    components  : 'Silverpeas-Components']

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 version of Silverpeas for which the documentation will be generated',
        name: 'SILVERPEAS_VERSION'
    )
  }

  environment {
    gitBaseRepo = 'https://github.com/Silverpeas/'
    gitCredential = 'cacc0467-7c85-41d1-bf4e-eaa470dd5e59'
    mavenRepo = 'https://nexus3.silverpeas.org/repository/silverpeas'
    releaseBranch = ''
  }

  stages {
    stage('Check version of Silverpeas') {
      when {
        expression { !isStableVersion() }
      }
      steps {
        error("Documentation is published only for a stable version. Version here is: ${params.SILVERPEAS_VERSION}")
      }
    }

    stage('Prepare the publishing') {
      steps {
        copyArtifacts projectName: "Silverpeas_Release", flatten: true,
            selector: specific(params.SILVERPEAS_VERSION)
        script {
          def report = readYaml file: 'release.yaml'
          releaseBranch = report.branch
        }
        sh 'rm -f release.yaml'
      }
    }

    stage('Publish documentation of Silverpeas Core') {
      when {
        expression { releaseBranch == 'master' }
      }
      steps {
        dir(projects.core) {
          git credentialsId: gitCredential, url: (gitBaseRepo + projects.core)
          sh """
            git checkout ${params.SILVERPEAS_VERSION}
            mvn site-deploy -Pdeployment -Djava.awt.headless=true -Dmaven.test.skip=true
            """
        }
      }
    }

    stage('Publish documentation of Silverpeas Components') {
      when {
        expression { releaseBranch == 'master' }
      }
      steps {
        dir(projects.components) {
          git credentialsId: gitCredential, url: (gitBaseRepo + projects.components)
          sh """
            git checkout ${params.SILVERPEAS_VERSION}
            mvn site-deploy -Pdeployment -Djava.awt.headless=true -Dmaven.test.skip=true
            """
        }
      }
    }

    stage('Publish Silverpeas Community Web Site') {
      steps {
        build job: 'Silverpeas Project Web Site Publisher', parameters: [
            string(name: 'SILVERPEAS_VERSION', value: params.SILVERPEAS_VERSION),
        ], wait: true
      }
    }
  }

  post {
    success {
      script {
        currentBuild.displayName = params.SILVERPEAS_VERSION
      }
    }
    always {
      step([$class                  : 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients              : "david.lesimple@silverpeas.org, sebastien.vuillet@silverpeas.org, aurore.allibe@silverpeas.org, miguel.moquillon@silverpeas.org, silveryocha@chastagnier.com",
            sendToIndividuals       : true])
    }
  }
}

String getBranch() {
  Matcher matcher = params.SILVERPEAS_VERSION =~ '^(\\d+.\\d+)\\..*$'
  matcher ? "${matcher[0][1]}.x" : 'master'
}

boolean isStableVersion() {
  Matcher m = params.SILVERPEAS_VERSION =~ '^\\d+.\\d+(.\\d+)?$'
  return m.matches()
}

String getDockerImageVersion() {
  Matcher matcher = params.SILVERPEAS_VERSION =~ '^(\\d+.\\d+)\\..*$'
  matcher ? "${matcher[0][1]}" : 'latest'
}