#!groovy

import groovy.json.JsonOutput

node('PODMAN') {
    String destRelease
    String logFileName = "build.log"

    try {
        stage('Clone git repo') {
            checkout scm
        }

        stage('Update includes') {
            Map latestReleases = readJSON(
                text: sh(
                    script: "./scripts/check_latest_releases.sh",
                    returnStdout: true,
                )
            )
            println("[+] Found the following latest releases:")
            println(latestReleases)

            if ("" != GIVEN_RELEASE) {
                println("[+] You have explicitely asked for the follwing release: ${GIVEN_RELEASE}")
                destRelease = GIVEN_RELEASE
            } else {
                destRelease = latestReleases[PLATFORM]['latest']
                println("[+] Using latest release ${destRelease} for ${PLATFORM}")
            }

            Integer exitStatus = sh( script: "./scripts/update_include.sh ${PLATFORM} ${destRelease}", returnStatus: true)
            if (0 != exitStatus) { throw new Exception("There was an error while trying to update include file") }
        }

        stage('Build kplatorms') {
            dir("${WORKSPACE}/build") {}
            sh "touch $logFileName"
            sh "podman build -t kplatforms:latest ."
            sh "podman unshare chown -R 1000:1000 ."
            // This allows the following command to write the log file if it's
            // is in the same directory
            sh "podman unshare chown 0:0 $logFileName"
            Integer exitStatus = sh(
                script: "podman run --rm -it -v $WORKSPACE:/src kplatforms:latest /src/scripts/build-kplatforms.sh $PLATFORM | tee $logFileName",
                returnStatus: true,
            )
            sh "podman unshare chown -R 0:0 ."
            if (0 != exitStatus) { throw new Exception("Build failure") }
        }

        stage('Archive Artifacts with Zip') {
            zip(zipFile: "build-${PLATFORM}.zip", archive: true, dir: 'build', overwrite: true)
        }

        stage('Check for removals') {
            List removed = []
            String buildLogs = readFile(logFileName)
            buildLogs.split('\n').each { line ->
                // Ignore Drupal9's log line that looks like:
                // 'Package operations: 190 installs, 0 updates, 0 removals'
                if (line.contains('remov') && ! line.contains (' 0 removals')) { removed.add(line) }
            }
            if ([] != removed) {
                currentBuild.result = 'UNSTABLE'
                println("[-] The following modules might have been removed, please advise:")
                println(removed)
            }
        }

        stage('Test kplatforms') {
            Integer exitStatus = sh(
                script: "podman run --rm -it -v $WORKSPACE:/src kplatforms:latest /src/scripts/test-kplatforms.sh $PLATFORM",
                returnStatus: true,
            )
            if (0 != exitStatus) { throw new Exception("Tests failed") }
        }
    } catch (exception) {
        println(exception)
        currentBuild.result = 'FAILURE'
        env.exception = JsonOutput.toJson([message: exception.message])
    } finally {
        // removes all files, sometimes want to keep some for debugging
        cleanWs()
    }
}
