#!/bin/sh
# Debian `postinst` maintainer script — runs after the package payload is
# unpacked. Wires /etc/apt/sources.list.d/paneflow.list at `pkg.paneflow.dev`
# so subsequent `apt upgrade paneflow` pulls new releases automatically
# (US-016).
#
# Guardrails (learned from the Cursor .deb `apt update` breakage —
# https://forum.cursor.com/t/installing-cursor-via-apt-deb-package-breaks-apt-update/132008):
#
#  - Idempotent: a pre-existing `paneflow.list` is left alone. Users who
#    point at a private mirror must keep their edits across reinstalls.
#  - Graceful GPG fetch: a failed network call at install time does NOT
#    abort the install. `apt update` will later complain about the
#    missing signature, and the printed message tells the user exactly
#    how to recover with `curl | gpg --dearmor`.
#  - Pure /bin/sh (no bashisms) — Debian Policy §4.9 and Ubuntu `dash`
#    compatibility.

set -e

KEYRING=/usr/share/keyrings/paneflow-archive.gpg
SOURCES=/etc/apt/sources.list.d/paneflow.list
KEY_URL=https://pkg.paneflow.dev/gpg
REPO_LINE='deb [signed-by=/usr/share/keyrings/paneflow-archive.gpg] https://pkg.paneflow.dev/apt stable main'

case "$1" in
configure)
    # --- Sources file --------------------------------------------------
    # Note on upgrade paths: a future release that moves `pkg.paneflow.dev`
    # to a new URL cannot repoint existing installs through this script —
    # the `[ ! -f "$SOURCES" ]` guard is strict so we never clobber a
    # user-customized mirror, and that same guard blocks our own URL
    # migrations. Such a migration will require either (a) a one-shot
    # `preinst` that removes the old file only if it matches the exact
    # previous canonical content, or (b) an in-release-notes manual
    # `rm /etc/apt/sources.list.d/paneflow.list && apt install …` instruction.
    if [ ! -f "$SOURCES" ]; then
        # The `signed-by=…` form is the post-`apt-key`-deprecation way to
        # pin a repo to a specific keyring. Debian Policy 12/Ubuntu 22.04+
        # require this; systems as old as Debian 11 also accept it.
        echo "$REPO_LINE" > "$SOURCES"
        chmod 644 "$SOURCES"
    fi

    # --- GPG keyring ---------------------------------------------------
    if [ ! -f "$KEYRING" ]; then
        fetch=""
        if command -v curl >/dev/null 2>&1; then
            fetch="curl -fsSL --max-time 30"
        elif command -v wget >/dev/null 2>&1; then
            fetch="wget -qO- --timeout=30"
        fi

        if [ -z "$fetch" ]; then
            cat >&2 <<EOF
PaneFlow: neither 'curl' nor 'wget' is installed, so the release signing
key at $KEY_URL was not fetched. The package is installed and usable.
To enable 'apt upgrade paneflow' later:

    sudo apt install -y curl
    sudo curl -fsSL $KEY_URL | sudo gpg --dearmor -o $KEYRING
    sudo apt update

EOF
        else
            # Stream the armored key through `gpg --dearmor` into a tmp
            # file, then validate it's a real OpenPGP keyring before
            # renaming to the live path. The validation matters because:
            # - A truncated fetch (network drop mid-stream) can produce a
            #   non-empty `$tmp` that `gpg --dearmor` wrote partial bytes
            #   to before failing. `[ -s … ]` alone would accept that.
            # - Cloudflare R2 behind the CDN could return an HTML error
            #   page with HTTP 200 (misconfiguration), which curl happily
            #   streams. Without validation we'd write garbage to the
            #   keyring and `apt update` would error cryptically.
            # `gpg --list-packets` parses the binary OpenPGP format and
            # exits non-zero on malformed input.
            tmp="$KEYRING.tmp.$$"
            if $fetch "$KEY_URL" 2>/dev/null | gpg --dearmor >"$tmp" 2>/dev/null \
               && [ -s "$tmp" ] \
               && gpg --list-packets "$tmp" >/dev/null 2>&1; then
                mv "$tmp" "$KEYRING"
                chmod 644 "$KEYRING"
            else
                rm -f "$tmp"
                cat >&2 <<EOF
PaneFlow: could not fetch the release signing key from $KEY_URL
(network unavailable at install time). The package is installed.
To enable 'apt upgrade paneflow' later:

    sudo curl -fsSL $KEY_URL | sudo gpg --dearmor -o $KEYRING
    sudo apt update

Without the key, 'apt update' will report a signature error on the
paneflow source, but all other apt operations keep working.

EOF
            fi
        fi
    fi

    # --- Icon + desktop cache refresh ----------------------------------
    # Without this, the freedesktop hicolor icon cache under
    # /usr/share/icons/hicolor/icon-theme.cache and the application DB
    # under /usr/share/applications/mimeinfo.cache keep pointing at the
    # previous version's artwork, so GNOME Shell / KDE Plasma / docks /
    # launchers keep showing stale icons after `apt upgrade paneflow`
    # even though the new PNGs are already on disk.
    #
    # Both commands are safe to re-run on every install and every
    # upgrade: they rebuild deterministically from the current
    # filesystem state. The `|| true` guard keeps the transaction
    # green on minimal Debian installs (server, some containers)
    # that don't ship these tools — the icons still work on any
    # desktop environment because the caches get rebuilt lazily.
    if command -v gtk-update-icon-cache >/dev/null 2>&1; then
        gtk-update-icon-cache -q -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
    fi
    if command -v update-desktop-database >/dev/null 2>&1; then
        update-desktop-database -q /usr/share/applications >/dev/null 2>&1 || true
    fi
    ;;

abort-upgrade|abort-deconfigure|abort-remove)
    # Rollback hooks — nothing to undo (file creations are idempotent
    # and will be re-tried on the next successful install).
    ;;

*)
    # Unknown action — exit 0 for forward compatibility with future
    # dpkg actions rather than hard-failing the install.
    ;;
esac

exit 0
