#!groovy

// Current version of this Pipeline https://github.com/VitexSoftware/BuildImages/blob/main/Test/Jenkinsfile

String[] distributions = [
//                      'debian:bookworm',   // python3-fastmcp not packaged for bookworm
                        'debian:trixie',
//                      'debian:forky',      // python3-fastmcp → python3-mcp missing in VitexSoftware forky repo
//                      'ubuntu:jammy',      // python3-fastmcp not packaged for jammy
//                      'ubuntu:noble',      // python3-fastmcp not packaged for noble
//                      'ubuntu:resolute',   // python3-fastmcp → python3-jsonref missing in VitexSoftware resolute repo
]

String vendor = 'vitexsoftware'

properties([
    copyArtifactPermission('*'),
    buildBlocker(
        useBuildBlocker: true,
        blockLevel: 'GLOBAL',
        scanQueueFor: 'ALL',
        blockingJobs: 'RebulidDEBRepoByAnsible'
    )
])

node() {
    ansiColor('xterm') {
        stage('SCM Checkout') {
            checkout scm
        }
    }
}

def branches = [:]
distributions.each { distro ->
    branches[distro] = {
        def distroName = distro
        println  "Dist:" + distroName

        def dist = distroName.split(':')
        def distroFamily = dist[0]
        def distroCode = dist[1]
        def buildImage = ''
        def artifacts = []
        def buildVer = ''

        node {
            ansiColor('xterm') {
                stage('Checkout ' + distroName) {
                    checkout scm
                    def imageName = vendor + '/' + distro
                    buildImage = docker.image(imageName)
                    sh 'git checkout debian/changelog'
                    def version = sh (
                        script: 'dpkg-parsechangelog --show-field Version',
                        returnStdout: true
                    ).trim()
                    buildVer = version + '.' + env.BUILD_NUMBER  + '~' + distroCode
                }
                stage('Build ' + distroName) {
                    buildImage.inside {
                        // Set unique build directories for this parallel build to avoid conflicts
                        def uniqueBuildId = env.BUILD_NUMBER + '-' + distroCode + '-' + env.EXECUTOR_NUMBER
                        sh '''
                            export DH_INTERNAL_BUILDDIR="/tmp/debhelper-build-''' + uniqueBuildId + '''"
                            export TMPDIR="/tmp/build-''' + uniqueBuildId + '''"
                            mkdir -p "$DH_INTERNAL_BUILDDIR" "$TMPDIR"
                        '''
                        sh 'dch -b -v ' + buildVer  + ' "' + env.BUILD_TAG  + '"'
                        sh 'sudo apt-get update --allow-releaseinfo-change'
                        sh 'sudo chown jenkins:jenkins ..'
                        sh 'sudo rm -rf debian/$(dpkg-parsechangelog --show-field Source)/ debian/.debhelper/ debian/tmp/'
                        sh '''
                            export DH_INTERNAL_BUILDDIR="/tmp/debhelper-build-''' + uniqueBuildId + '''"
                            export TMPDIR="/tmp/build-''' + uniqueBuildId + '''"
                            debuild-pbuilder -r"sudo -E" -i -us -uc -b
                        '''
                        sh 'mkdir -p $WORKSPACE/dist/debian/ ; rm -rf $WORKSPACE/dist/debian/* ; for deb in $(cat debian/files | awk \'{print $1}\'); do mv "../$deb" $WORKSPACE/dist/debian/; done'
                        artifacts = sh (
                            script: "cat debian/files | awk '{print \$1}'",
                            returnStdout: true
                        ).trim().split('\n')
                    }
                }

                stage('Test ' + distroName) {
                    buildImage.inside {
                        def debconf_debug = 0 //Set to "5" or "developer" to debug debconf
                        sh 'cd $WORKSPACE/dist/debian/ ; dpkg-scanpackages . /dev/null > Packages; gzip -9c Packages > Packages.gz; cd $WORKSPACE'
                        sh 'echo "deb [trusted=yes] file://///$WORKSPACE/dist/debian/ ./" | sudo tee /etc/apt/sources.list.d/local.list'
                        sh 'sudo apt-get update --allow-releaseinfo-change'
                        sh 'echo "INSTALATION"'

                        def installOrder = [
//                        '',
                        ]

                        def sorted_artifacts = artifacts.toList()

                        // If installOrder is empty, install all produced packages
                        if (installOrder.isEmpty()) {
                            sorted_artifacts.each { deb_file ->
                                if (deb_file.endsWith('.deb')) {
                                    def pkgName = deb_file.tokenize('/')[-1].replaceFirst(/_.*/, '')
                                    sh 'echo -e "${GREEN} installing ' + pkgName + ' on `lsb_release -sc` ${ENDCOLOR} "'
                                    sh 'sudo DEBIAN_FRONTEND=noninteractive DEBCONF_DEBUG=' + debconf_debug + ' apt-get -y install ' + pkgName
                                }
                            }
                        } else {
                            // Install packages in specified order
                            installOrder.each { pkgPrefix ->
                                def debFile = null
                                for (item in sorted_artifacts) {
                                    def itemStr = item.toString()
                                    if (itemStr.startsWith(pkgPrefix) && itemStr.endsWith('.deb')) {
                                        debFile = itemStr
                                        break
                                    }
                                }
                                if (debFile) {
                                    def pkgName = debFile.tokenize('/')[-1].replaceFirst(/_.*/, '')
                                    sh 'echo -e "${GREEN} installing ' + pkgName + ' on `lsb_release -sc` ${ENDCOLOR} "'
                                    sh 'sudo DEBIAN_FRONTEND=noninteractive DEBCONF_DEBUG=' + debconf_debug + ' apt-get -y install ' + pkgName
                                }
                            }
                        }
                    }
                }
                stage('Archive artifacts ' + distroName) {
                    buildImage.inside {
                        artifacts.each { deb_file ->
                            println "Archiving artifact: " + deb_file
                            archiveArtifacts artifacts: 'dist/debian/' + deb_file
                        }

                        def uniqueBuildId = env.BUILD_NUMBER + '-' + distroCode + '-' + env.EXECUTOR_NUMBER
                        sh '''
                            set -e
                            if [ -f debian/files ]; then
                              while read -r file _; do
                                [ -n "$file" ] || continue
                                rm -f "dist/debian/$file" || true
                                rm -f "../$file" || true
                                rm -f "$WORKSPACE/$file" || true
                              done < debian/files
                            fi
                            rm -rf "/tmp/debhelper-build-''' + uniqueBuildId + '''" || true
                            rm -rf "/tmp/build-''' + uniqueBuildId + '''" || true
                        '''
                    }
                }
            }
        }
    }
}

parallel branches

node {
    stage('Publish to Aptly') {
        publishDebToAptly()
    }
}
