// Release pipeline for the Qt6-migrated legatus validation-scope branch
// (story/release-validation-scope): TetraIF, Z, Lts/Common (+
// Lts/Proxies/TrainingAreaBase) -> 5 release DEB packages.
//
// Workspace layout (checked out by Jenkins, outer pipeline repo):
//   <WORKSPACE>/
//     rti_license.dat
//     external/
//     qt-migration-legatus/qt6-after/qt6-migrated-legatus/   <- LEGATUS_ROOT
//       Dockerfile                     (prebuilt build image recipe)
//       new_docker_build.sh            (local build driver)
//       rpmbuild/make_rpm_ubuntu26.py  (in-tree packaging)
//       jenkins-ci-rme/                (this pipeline)
//
// The build container image is the prebuilt image built from the in-tree
// Dockerfile; it is built on the agent when not present (RebuildImage
// forces a fresh build).

def project = 'guez'
def legatusRoot = 'qt-migration-legatus/qt6-after/qt6-migrated-legatus'
def imageName = 'legatus-qt6-prebuilt:latest'

properties([
    disableConcurrentBuilds(),
    parameters([
        string(name: 'OsVersions', defaultValue: '26.04', description: 'Comma-separated Ubuntu base versions, all built in parallel'),
        string(name: 'LtsVersion', defaultValue: '1.0', description: 'LTS version (major.minor) passed to make_rpm_ubuntu26.py --version'),
        booleanParam(name: 'ClearWorkspace', defaultValue: false, description: 'Clear entire workspace on all nodes used for build'),
        booleanParam(name: 'PublishArtifactRepo', defaultValue: true, description: 'Upload produced DEBs to the internal artifact repository'),
        booleanParam(name: 'RebuildImage', defaultValue: false, description: 'Rebuild the prebuilt build image from the in-tree Dockerfile (default: reuse when present)')
    ])
])

env.GIT_TERMINAL_PROMPT = '0'
env.LTS_VERSION = "${params.LtsVersion}"
env.ARTIFACTREPO = 'https://internal-repo.sl.defence-elec.de'

// OS versions this build covers; every build is isolated under
// rpms/${project}/${osVersion} so concurrent OS builds never collide.
def osVersions = params.OsVersions.split(',').collect { it.trim() }.findAll { it }

def builds = [:]
osVersions.each { osVersion ->
    def rpmsDir = "rpms/${project}/${osVersion}"

    builds["${project} (${osVersion})"] = {
        stage("Prepare ${project} (${osVersion})") {
            sh "rm -rf ${rpmsDir}"
            sh "mkdir -p ${rpmsDir}"
        }

        stage("Prepare build image ${project} (${osVersion})") {
            if (params.RebuildImage) {
                sh "docker rmi ${imageName} || true"
            }
            // The in-tree driver owns the Dockerfile build args (APT_PACKAGES,
            // QT_VERSION, ...) - single source of truth.
            sh """
                if docker image inspect ${imageName} >/dev/null 2>&1; then
                    echo "Reusing existing prebuilt image ${imageName}"
                else
                    echo "Building prebuilt image ${imageName} from the in-tree Dockerfile..."
                    cd ${legatusRoot} && bash ./new_docker_build.sh --build-prebuilt-image --docker-image ${imageName}
                fi
            """
        }

        stage("Build DEB ${project} (${osVersion})") {
            def buildContainer = docker.image("${imageName}")
            def guezMode = (project == 'guez') ? 'ON' : 'OFF'

            def dockerOpts = "--init --shm-size=2g" +
                             " -v ${WORKSPACE}:/workspace" +
                             " -e WORKSPACE=/workspace" +
                             " -e PROJECT_BASE_DIR=/workspace" +
                             " -e PROJECT=${project}" +
                             " -e OS_VERSION=${osVersion}" +
                             " -e LTS_VERSION=${LTS_VERSION}" +
                             " -e GUEZ_MODE=${guezMode}" +
                             " -e BUILD_NUMBER=${env.BUILD_NUMBER}" +
                             " -e BUILD_TAG=${env.BUILD_TAG}"

            buildContainer.inside(dockerOpts) {
                sh "bash /workspace/${legatusRoot}/jenkins-ci-rme/jenkins_builder_ubuntu26.sh"
            }
        }

        stage("Publish ${project} (${osVersion})") {
            if (params.PublishArtifactRepo) {
                withCredentials([usernamePassword(credentialsId: 'internal-repo-uploader',
                                                  usernameVariable: 'CURL_USER',
                                                  passwordVariable: 'CURL_PASS')]) {
                    sh """
                        export CURL_CRED="\${CURL_USER}:\${CURL_PASS}"
                        export PROJECT='${project}'
                        export OS_VERSION='${osVersion}'
                        export LTS_VERSION='${LTS_VERSION}'
                        export BUILD_NUMBER='${env.BUILD_NUMBER}'
                        export ARTIFACTREPO='${env.ARTIFACTREPO}'
                        export ARTIFACTFOLDER='${project}'
                        bash ${legatusRoot}/jenkins-ci-rme/jenkins_publisher_ubuntu26.sh
                    """
                }

                def tdsUrl     = readFile("url-${project}-${osVersion}.txt").trim()
                def tdsVersion = readFile("tdsversion-${project}-${osVersion}.txt").trim()
                def link = """<a href="${tdsUrl}" target="_blank">${project} ${tdsVersion} (OS ${osVersion})</a>"""
                currentBuild.description = currentBuild.description ? "${currentBuild.description}<br/>${link}" : link
            } else {
                echo "Artifact-repo publish skipped for ${project} (OS ${osVersion}, PublishArtifactRepo=false)"
            }
        }
    }
}

try {
    stage("Initialization") {
        if (params.ClearWorkspace) {
            cleanWs()
            checkout([
                $class: 'GitSCM',
                branches: scm.branches,
                doGenerateSubmoduleConfigurations: false,
                extensions: [[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', trackingSubmodules: false]],
                userRemoteConfigs: scm.userRemoteConfigs
            ])
        }
        echo "Legatus Qt6 release build initialized — branch '${env.BRANCH_NAME}', project: ${project}, LTS ${env.LTS_VERSION}, OS version(s): ${osVersions.join(', ')}"
    }

    parallel builds

    stage("Finalization") {
        echo "Legatus Qt6 release build completed — project: ${project} (LTS ${env.LTS_VERSION}), OS version(s): ${osVersions.join(', ')}"
    }

    currentBuild.result = 'SUCCESS'
} catch (e) {
    currentBuild.result = 'FAILURE'
    throw e
}
