pipeline {
  agent none
  parameters {
    string(name: 'RELEASE', description: 'Release numeric name (e.g. 2022.10.01)', trim: true)
    string(name: 'PACKAGER_LIST', description: 'List of projects with debian package(s) (packagers) to build for this release separated with , (e.g. xivo,xivo-confgend,xivo-sysconfd)', trim: true)
    string(name: 'SOURCE', description: 'The source release the new one is built from (e.g. xivo-2024.10-latest)', trim: true)
    booleanParam(name: 'SKIP_BUMP_XIVO', defaultValue: false, description: 'Skip the bump-xivo stage (it already completed in a previous run).')
    booleanParam(name: 'SKIP_TAG', defaultValue: false, description: 'Skip the simulate-tag and apply-tag stages. xivo-multi-tag already skips the projects it has tagged, so replaying them is harmless; use this to go straight to the stage that failed.')
    booleanParam(name: 'SKIP_LOCAL_REPO', defaultValue: false, description: 'Skip the create-local-rc stage (the local repository already exists).')
    booleanParam(name: 'SKIP_PACKAGES', defaultValue: false, description: 'Skip the build-packages stage (every packager already built).')
    booleanParam(name: 'SKIP_RELEASE_RC', defaultValue: false, description: 'Skip the create-release-rc stage.')
  }
  stages {
    stage('welcome') {
      agent any
      input {
        message "Ready to start building XiVO ${RELEASE}?"
        ok "Yes, go go go !"
      }
      steps {
        echo "Welcome to this new RC build for XiVO ${RELEASE}!"
      }
    }
    stage('bump-xivo') {
      when {
        expression { !params.SKIP_BUMP_XIVO }
      }
      agent any
      steps {
        echo "Bumping xivo project if necessary"
        sh 'set -xe; ci-bump-xivo ${RELEASE}'
      }
    }
    stage('simulate-tag') {
      when {
        expression { !params.SKIP_TAG }
      }
      agent any
      steps {
        echo "Simulating the package tagging automation"
        sh 'set -xe; xivo-multi-tag rc ${RELEASE} --dry-run ${PACKAGER_LIST}'
        echo "Simulation done !"
      }
    }
    stage('apply-tag') {
      when {
        expression { !params.SKIP_TAG }
      }
      agent any
      input {
        message "Tag ${PACKAGER_LIST} like the simulation ?"
        ok "Ready"
      }
      steps {
        echo "Tagging for real"
        sh 'set -xe; xivo-multi-tag rc ${RELEASE} ${PACKAGER_LIST}'
        echo "Tagging done !"
      }
    }
    stage('create-local-rc') {
      when {
        expression { !params.SKIP_LOCAL_REPO }
      }
      agent any
      input {
        message "Click \"Create local repo\" to continue."
        ok "Create local repo"
      }
      steps {
        echo "Creating local repo xivo-${RELEASE}"
        build(
            job: 'create-local-repository',
            parameters: [
                string(name: 'REPOSITORY_NAME', value: "xivo-${RELEASE}"),
                string(name: 'PUBLISH', value: "yes"),
                string(name: 'REPOSITORY', value: "archive")],
                wait: true)
        echo "Local repo xivo-${RELEASE} was created."
      }
    }
    stage('build-packages') {
      when {
        expression { !params.SKIP_PACKAGES }
      }
      agent any
      input {
        message "Click \"Build packages\" to continue."
        ok "Build packages"
      }
      steps {
        echo "Now build job will be ran for each package: ${PACKAGER_LIST}."
        echo "And they will be launched with these parameters:"
        echo "- TAG_OR_BRANCH=${RELEASE}-rc"
        echo "- BUILD_TYPE=rc"

        script {
          def packagers = "$PACKAGER_LIST".split(",").collect { it.trim() }.findAll { it }

          def alreadyBuilt = []
          def built = []
          def failed = []

          packagers.each { packager ->
            def jobStatus = build job: packager,
            propagate: false,
            parameters: [
              string(name: 'BRANCH_OR_TAG', value: "$RELEASE-rc" ),
              string(name: 'BUILD_TYPE', value: 'rc')
            ]

            if (jobStatus.result == 'SUCCESS' || jobStatus.result == 'UNSTABLE') {
              echo "Job for ${packager} was successful."
              built << packager
              return
            }

            def buildLog = sh(
              script: "curl -s -X GET http://localhost:8080/job/${packager}/${jobStatus.number}/consoleText",
              returnStdout: true
            )
            if (buildLog.contains("${params.RELEASE} is already tagged, cannot continue.")) {
              echo "Build job for ${packager} has been already ran."
              alreadyBuilt << packager
            } else {
              echo "Build job for ${packager} has failed."
              failed << packager
            }
          }

          echo """Debian build summary for ${params.RELEASE}:
- built now: ${built.join(', ') ?: 'none'}
- already built: ${alreadyBuilt.join(', ') ?: 'none'}
- failed: ${failed.join(', ') ?: 'none'}"""

          if (failed) {
            error "Debian build incomplete. Rerun this job with SKIP_BUMP_XIVO, SKIP_TAG and SKIP_LOCAL_REPO checked and PACKAGER_LIST set to: ${failed.join(',')}"
          }

          echo "All packages are built."
        }
      }
    }
    stage('create-release-rc') {
      when {
        expression { !params.SKIP_RELEASE_RC }
      }
      agent any
      input {
        message "Click \"Release RC\" to continue."
        ok "Release RC"
      }
      steps {
        echo "Launching job create-rc-for-release with"
        echo "- NAME=xivo-${RELEASE}"
        echo "- SOURCE=${SOURCE}"
        echo "- BUILT_PACKAGES=${PACKAGER_LIST}"
        build(
            job: 'create-rc-for-release',
            parameters: [
                string(name: 'NAME', value: "xivo-${RELEASE}"),
                string(name: 'SOURCE', value: "${SOURCE}"),
                string(name: 'BUILT_PACKAGES', value: "${PACKAGER_LIST}")],
            wait: true)
        echo "Created rc for release from xivo-${RELEASE}."
      }
    }
  }
}
