#!/bin/sh
set -e

DB_DIR=/var/lib/jray-server

if [ -d /run/systemd/system ]; then
    systemctl --system daemon-reload >/dev/null 2>&1 || true
fi

case "$1" in
purge)
    # Configuration goes, including the TMDB key.
    rm -f /etc/jray-server/env
    rmdir --ignore-fail-on-non-empty /etc/jray-server 2>/dev/null || true

    if [ -f /usr/share/debconf/confmodule ]; then
        . /usr/share/debconf/confmodule
        db_purge || true
    fi

    if [ -x /usr/bin/deb-systemd-helper ]; then
        deb-systemd-helper purge jray-server.service >/dev/null || true
        deb-systemd-helper unmask jray-server.service >/dev/null || true
    fi

    # The database is deliberately NOT deleted on purge, and that is a knowing
    # deviation from the usual expectation that purge removes everything.
    #
    # Manifests are the output of real CV compute on media the operator may no
    # longer have, and federation (SPEC section 9a) gives partial resilience but
    # is explicitly not a backup. Silently destroying that during an `apt purge`
    # - a command people run to clean up - is not a trade worth making for
    # tidiness. Say where it is instead, and let the operator decide.
    if [ -d "$DB_DIR" ]; then
        echo "jray-server: purged, but the database was kept at $DB_DIR" >&2
        echo "             It holds contributed manifests, which are not recoverable" >&2
        echo "             from this package. Remove it yourself if you mean to:" >&2
        echo "                 rm -rf $DB_DIR" >&2
    fi
    ;;

remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
    if [ "$1" = remove ] && [ -x /usr/bin/deb-systemd-helper ]; then
        deb-systemd-helper mask jray-server.service >/dev/null || true
    fi
    ;;

*) echo "postrm called with unknown argument \`$1'" >&2; exit 1 ;;
esac

exit 0
