#!/bin/bash
# NetCell MailGuard self-upgrade helper.
#
# Invoked via sudo from nmg-api when the operator confirms the GUI
# update prompt. Fully detaches into a systemd-run transient unit so
# apt-get can happily kill/replace the very nmg-api process that
# triggered us.
#
# The path is pinned in deploy/sudoers.d/nmg — no arguments, no env,
# so this cannot be used to run arbitrary apt operations.
set -euo pipefail
# C-Locale erzwingen damit apt/dpkg/systemctl-Output deterministisch
# Englisch ist — sonst matchen Pipe-Parser unter de_DE/fr_FR/...
# nicht (Befund 2026-05-03: Installer-Abbruch wegen
# „Installationskandidat:" statt „Candidate:"). Wirkt nur in dieser
# Skript-Laufzeit + den von systemd-run gestarteten Kindprozessen.
export LC_ALL=C
export LANG=C
export DEBIAN_FRONTEND=noninteractive

UNIT=nmg-upgrade.service
systemctl reset-failed "$UNIT" 2>/dev/null || true

exec systemd-run \
    --unit="$UNIT" \
    --collect \
    --description="NetCell MailGuard Upgrade" \
    /bin/bash -c '
        set -e
        export LC_ALL=C
        export LANG=C
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq || true
        # No --only-upgrade: when a release adds a new Depends entry
        # (e.g. nmg-keydb after the KeyDB-Active-Active migration),
        # `apt install nmg` resolves and pulls the new dependency.
        # `apt install --only-upgrade nmg` would have left the host
        # with a half-installed nmg and a broken depends chain.
        # Plain `apt install nmg` upgrades nmg and any of its
        # dependencies it newly requires; it does NOT touch unrelated
        # packages.
        apt-get install -y nmg

        # rspamd auf upstream-Version hochziehen WENN das nmg-Postinst
        # gerade das rspamd.com-Repo + Pin gedroppt hat (1.8.42+). Wir
        # machen das hier statt im Postinst weil ein nested apt-get
        # install im Postinst gegen den eigenen dpkg-Lock konfligiert
        # — dieses Script läuft als detached systemd-run-Unit OUTSIDE
        # der Original-Transaktion, also kein Lock-Konflikt.
        # apt-cache madison filtert auf das rspamd.com-Repo: wenn der
        # Postinst es noch nicht installiert hat (älteres nmg), bleibt
        # das hier no-op und rspamd bleibt auf seiner aktuellen Version.
        if apt-cache madison rspamd 2>/dev/null | grep -q "rspamd.com"; then
            apt-get install -y --only-upgrade rspamd 2>&1 || true
            for i in 1 2 3 4 5; do
                systemctl is-active --quiet rspamd && break
                sleep 2
            done
            if ! systemctl is-active --quiet rspamd; then
                echo "ERROR: rspamd nicht aktiv nach Upgrade — Mail-Pipeline pruefen!" >&2
            fi
        fi
    '
