#!/usr/bin/env bash
# install-protect — put parvagues-protect where root can safely run it.
#
#     sudo tools/install-protect.sh            install + enable + start
#     sudo tools/install-protect.sh --uninstall
#
# WHY THE SCRIPT IS COPIED INSTEAD OF SYMLINKED
# ---------------------------------------------
# The user unit for the watchdog runs straight out of the repo, which is fine —
# it runs as PLN, and PLN owns the repo. This one runs as ROOT. A root systemd
# unit whose ExecStart lives under /home/pln is a privilege-escalation hole:
# anything able to write that file (a bad npm postinstall, a stray script, a
# future me) gets root on the next boot. So the script is COPIED to
# /usr/local/bin and owned by root:root 755. The repo keeps the source of truth;
# re-run this after editing it.
set -euo pipefail

SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN=/usr/local/bin/parvagues-protect
UNIT=/etc/systemd/system/parvagues-protect.service

if [ "$(id -u)" -ne 0 ]; then
  echo "needs root: sudo $0 $*" >&2
  exit 1
fi

if [ "${1:-}" = "--uninstall" ]; then
  systemctl disable --now parvagues-protect.service 2>/dev/null || true
  rm -f "$BIN" "$UNIT"
  systemctl daemon-reload
  echo "removed $BIN and $UNIT"
  exit 0
fi

install -o root -g root -m 0755 "$SRC_DIR/parvagues-protect.sh" "$BIN"
install -o root -g root -m 0644 "$SRC_DIR/parvagues-protect.service" "$UNIT"

systemctl daemon-reload
systemctl enable --now parvagues-protect.service

sleep 3
echo
systemctl --no-pager --lines=8 status parvagues-protect.service || true
echo
echo "--- current protection ---"
"$BIN" --check || true

cat <<'EOF'

--- prove it actually recovers (the whole point) ---
The failure this fixes only appears AFTER a restart, so verifying it at rest
proves nothing. Restart SuperDirt and watch the score come back on its own:

    systemctl --user restart parvagues-sc
    sleep 12 && /usr/local/bin/parvagues-protect --check
    journalctl -u parvagues-protect -n 20 --no-pager

Expect a journal line naming the NEW pid and `oom:200->-1000`. If instead the
check says UNPROTECTED, the daemon is not seeing the process — look at pids_for.
EOF
