pipeline {
  agent none
  parameters {
    string(name: 'RELEASE', description: 'Release numeric name (e.g. 2022.10.01)', trim: true)
    string(name: 'DOCKER_LIST', description: 'List of projects with docker images to build for this release separated with , (e.g. xucserver,xivo-agid,edge-coturn)', trim: true)
    string(name: 'LTS_BRANCH', description: 'The name of the LTS branch (e.g. 2022.10, 2023.10, or master)', trim: true)
  }
  stages {
    stage('build-docker-images') {
      agent any
      input {
        message "Click \"Build docker images\" to continue."
        ok "Build docker images"
      }
      steps {
        echo "Now build job will be ran for each docker image: ${DOCKER_LIST}."
        echo "And they will be launched with these parameters:"
        echo "- TAG_OR_BRANCH=${LTS_BRANCH}"
        echo "- BUILD_MODE=rc"
        script {
          def jobNames = "$DOCKER_LIST".split(",")

          jobNames.each { jobName ->
            def job_exec_status = build job: "${jobName}-docker-auto-v2",
            propagate: false,
            parameters: [
              string(name: 'BRANCH_OR_TAG', value: "$LTS_BRANCH" ),
              string(name: 'BUILD_MODE', value: 'rc')
            ]
            if(job_exec_status.result == 'SUCCESS' || job_exec_status.result == 'UNSTABLE'){
              echo "Job for ${jobName} was successful."
            } else {
              def apiRequest = "http://localhost:8080/job/${jobName}/${job_exec_status.number}/consoleText"
              def buildLog = sh(script: "curl -s -X GET ${apiRequest}", returnStdout: true)
              if (buildLog.contains("${params.RELEASE} is already tagged, cannot continue.")) {
                echo "Build job for ${jobName} has been already ran."
                return
              }
              if (buildLog.contains("is already tagged, cannot continue.")) {
                error "${params.RELEASE} TARGET_VERSION is not bumped. Exiting pipeline."
                return
              }
              error "Build job for ${jobName} has failed. Exiting pipeline."
            }
          }
        }
        echo "All docker images are built."
      }
    }
  }
}
