#!/usr/bin/env bash
# install.sh — arm (or disarm) the notification gate. Run as root: deck-sudo bash install.sh
#
# dpkg-divert keeps libnotify-bin's binary at /usr/bin/notify-send.real across package
# upgrades; /usr/bin/notify-send becomes the gate. Idempotent, fail-closed.
set -uo pipefail

LIB=/usr/local/lib/notif-gate
GATE=$LIB/notif_gate.py
TARGET=/usr/bin/notify-send
REAL=/usr/bin/notify-send.real
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

fail() { printf 'notif-gate install: %s\n' "$1" >&2; exit 1; }
[[ $EUID -eq 0 ]] || fail "must run as root (deck-sudo bash $0)"

divert_present() { dpkg-divert --list "$TARGET" 2>/dev/null | grep -q "$REAL"; }

if [[ "${1:-}" == "--uninstall" ]]; then
  [[ -L "$TARGET" ]] && rm -f "$TARGET"
  divert_present && { dpkg-divert --remove --rename "$TARGET" >/dev/null || fail "divert removal failed"; }
  rm -rf "$LIB"
  printf 'notif-gate: disarmed; %s restored\n' "$TARGET"
  exit 0
fi

[[ -f "$SRC_DIR/notif_gate.py" ]] || fail "gate source missing at $SRC_DIR/notif_gate.py"

if ! divert_present; then
  [[ -e "$TARGET" && ! -L "$TARGET" ]] || fail "$TARGET is missing or already a link — refusing to divert an unknown state"
  dpkg-divert --divert "$REAL" --rename "$TARGET" >/dev/null || fail "dpkg-divert failed"
fi
[[ -x "$REAL" ]] || fail "real emitter absent at $REAL after divert"

install -d -m 0755 "$LIB" || fail "cannot create $LIB"
install -m 0755 -o root -g root "$SRC_DIR/notif_gate.py" "$GATE" || fail "cannot install gate"
ln -sfn "$GATE" "$TARGET" || fail "cannot link $TARGET"

[[ "$(readlink -f "$TARGET")" == "$GATE" ]] || fail "verification failed: $TARGET does not resolve to $GATE"
printf 'notif-gate: armed — %s -> %s (real emitter at %s)\n' "$TARGET" "$GATE" "$REAL"
