pipeline {
    agent any

    options {
        skipDefaultCheckout(true)
        disableConcurrentBuilds()
        timestamps()
    }

    environment {
        KERNEL_JOB = 'espos-kernel'
        APTLY_REPO = 'espos-unstable'
        APTLY_HOST = 'ubuntu@elordenador.org'
        APTLY_SSH_HOST = 'elordenador.org'
    }

    stages {
        stage('Checkout') {
            steps {
                deleteDir()
                checkout scm
            }
        }

        stage('Download kernel artifacts') {
            steps {
                // Copy Artifact plugin: latest successful build of espos-kernel.
                copyArtifacts(
                    projectName: env.KERNEL_JOB,
                    selector: lastSuccessful(stable: false),
                    filter: '**/linux-image-*-espos_*.deb,**/linux-headers-*-espos_*.deb',
                    target: 'kernel-artifacts',
                    flatten: true,
                    optional: false
                )
                sh 'find kernel-artifacts -maxdepth 1 -type f -name "*.deb" -print'
            }
        }

        stage('Install build dependencies') {
            steps {
                sh '''
                    set -eu
                    sudo apt-get update
                    sudo apt-get install -y dpkg-dev lintian
                '''
            }
        }

        stage('Build metapackage') {
            steps {
                sh '''
                    set -eu
                    ./scripts/build-metapackage kernel-artifacts dist
                    dpkg-deb --info dist/espos-kernel_*.deb
                '''
            }
        }

        stage('Lintian') {
            steps {
                sh 'lintian dist/espos-kernel_*.deb'
            }
        }

        stage('Publish in Aptly') {
            steps {
                sshagent(['srv01_elordenador_org']) {
                    withCredentials([
                        string(credentialsId: 'aptly_gpg_pass', variable: 'GPG_PASS')
                    ]) {
                        sh '''
                            set -eu

                            remote_dir="/tmp/espos-kernel-metapackage-${BUILD_TAG}"
                            mkdir -p "$HOME/.ssh"
                            chmod 700 "$HOME/.ssh"
                            ssh-keyscan -H "$APTLY_SSH_HOST" >> "$HOME/.ssh/known_hosts"

                            ssh "$APTLY_HOST" "mkdir -p '$remote_dir' && chmod 700 '$remote_dir'"
                            trap 'ssh "$APTLY_HOST" "rm -rf '\''$remote_dir'\''"' EXIT HUP INT TERM
                            scp dist/espos-kernel_*.deb "$APTLY_HOST:$remote_dir/"

                            # The passphrase travels over SSH stdin and is never an argument.
                            printf '%s' "$GPG_PASS" | ssh "$APTLY_HOST" \
                                "umask 077; cat > '$remote_dir/gpg-passphrase'"

                            ssh "$APTLY_HOST" "
                                set -eu
                                aptly repo add -force-replace '$APTLY_REPO' '$remote_dir'/espos-kernel_*.deb

                                if aptly publish list -raw | grep -Eq '^[^[:space:]]+[[:space:]]+$APTLY_REPO$'; then
                                    aptly publish update \
                                        -passphrase-file='$remote_dir/gpg-passphrase' \
                                        '$APTLY_REPO'
                                else
                                    aptly publish repo \
                                        -distribution='$APTLY_REPO' \
                                        -component=main \
                                        -passphrase-file='$remote_dir/gpg-passphrase' \
                                        '$APTLY_REPO'
                                fi
                            "
                        '''
                    }
                }
            }
        }
    }

    post {
        always {
            archiveArtifacts artifacts: 'dist/espos-kernel_*.deb', fingerprint: true, allowEmptyArchive: true
        }
        success {
            echo 'Metapaquete espos-kernel publicado correctamente'
        }
        failure {
            echo 'Error construyendo o publicando espos-kernel'
        }
    }
}
