#!/bin/sh
# Threshold package post-remove script (deb "postrm" / rpm "%postun").
#
# deb: $1 is remove|purge|upgrade|...    rpm: $1 is 0 (erase) or 1+ (upgrade)
#
# On final removal this removes only what the Threshold package scripts
# themselves created: the managed systemd drop-in, the /usr/bin/boundary and
# /etc/systemd/system/boundary.service symlinks (only if they point at
# Threshold), and on purge the "threshold" user. User configuration, data and
# the legacy "boundary" user are never touched.
#
# THRESHOLD_PKG_ROOT exists only so the logic can be exercised by
# .release/linux/test/test-package-scripts.sh without root; it is empty in
# normal use.

set -eu

ROOT="${THRESHOLD_PKG_ROOT:-}"
SYSTEMD_ETC="$ROOT/etc/systemd/system"
DROPIN_DIR="$SYSTEMD_ETC/threshold.service.d"
DROPIN="$DROPIN_DIR/10-legacy-boundary-user.conf"
DROPIN_MARK="# Managed by the Threshold package (legacy boundary user reuse)"

# rm a symlink only if its target's basename matches $2.
rm_link_if() {
	if [ -L "$1" ]; then
		_t=$(readlink "$1" || true)
		case "${_t##*/}" in
		"$2") rm -f "$1" ;;
		esac
	fi
}

case "${1:-}" in
remove | purge | 0)
	rm_link_if "$ROOT/usr/bin/boundary" threshold
	rm_link_if "$SYSTEMD_ETC/boundary.service" threshold.service
	rm_link_if "$SYSTEMD_ETC/multi-user.target.wants/threshold.service" threshold.service
	if [ -f "$DROPIN" ] && grep -qF "$DROPIN_MARK" "$DROPIN"; then
		rm -f "$DROPIN"
		rmdir "$DROPIN_DIR" 2>/dev/null || true
	fi
	if command -v systemctl >/dev/null 2>&1 && [ -d "$ROOT/run/systemd/system" ]; then
		systemctl daemon-reload >/dev/null 2>&1 || true
	fi
	;;
esac

if [ "${1:-}" = "purge" ]; then
	if id -u threshold >/dev/null 2>&1; then
		userdel threshold || true
	fi
fi

exit 0
