#!/bin/sh
# prerm for the privacyfence .deb.
#
# Every install is privilege-separated (ADR 0003 decision 5): postinst's machine half leaves a
# system unit, privacyfence-daemon.service, running as the privacyfence account, plus an XDG
# autostart entry for the companion. Neither is a dpkg-tracked file -- the separation tool renders
# both -- so dpkg would leave them behind, pointing at a binary it has just deleted.
#
# `remove` (also the first step of a purge from an installed state) runs `uninstall` (ADR 0042)
# while /usr/sbin/privacyfence-privilege-separation still exists: it stops and disables the unit
# and removes both rendered files. It leaves /var/lib/privacyfence, the marker in it and the
# privacyfence account and group alone, so a later reinstall finds the same data; debian/postrm's
# `purge` case is what deletes those. Nothing here reaches into a user's $HOME, and nothing moves
# data into one. Best-effort (`|| true`): a removal must never fail on it.
#
# `upgrade` only stops the unit. A separated install's daemon runs the packaged PyInstaller onedir
# build straight out of /opt/privacyfence, and dpkg unpacks the new version's files over that same
# directory *before* postinst runs -- a lazily loaded shared library can vanish out from under the
# still-running old process mid-upgrade and crash it. Stopping first avoids that window;
# postinst's machine half, which already runs on every upgrade (see its own comment), starts the
# unit again once the new files are in place, so this never leaves the daemon down. `|| true`
# because `systemctl stop` on a unit that was never installed just fails.
set -e

case "$1" in
    remove)
        if [ -x /usr/sbin/privacyfence-privilege-separation ]; then
            /usr/sbin/privacyfence-privilege-separation uninstall || true
        fi
        ;;
    upgrade)
        if command -v systemctl >/dev/null 2>&1; then
            systemctl stop privacyfence-daemon.service >/dev/null 2>&1 || true
        fi
        ;;
    deconfigure)
        ;;
    failed-upgrade)
        ;;
    *)
        ;;
esac

exit 0
