#!/usr/bin/env bash
# notif-approve — the human-only approval action for the desktop notification gate.
#
#   notif-approve pending             what is being swallowed, and what it would say
#   notif-approve approve <id>...     let those sources notify you   (TTY, human only)
#   notif-approve revoke  <id>...     silence them again             (TTY, human only)
#   notif-approve approved            what is currently allowed
#   notif-approve forget <id>...      drop a pending record you do not care about
#                                     (grants nothing — it returns if the source tries again)
#
# approve/revoke are the ONLY writers of the approved registry and refuse every
# non-human caller with exit 77, the same contract as cld-unsafe/cdx-unsafe.
set -uo pipefail

GATE="${NOTIF_GATE_PY:-/usr/local/lib/notif-gate/notif_gate.py}"
SESSION_LIB="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../lib/session-class.sh"

[[ -f "$GATE" ]] || {
  printf 'notif-approve: gate not installed at %s\n' "$GATE" >&2
  printf 'arm it: deck-sudo bash <overdeck>/modules/security/notif-gate/install.sh\n' >&2
  exit 1
}
# shellcheck source=../lib/session-class.sh
[[ -f "$SESSION_LIB" ]] && source "$SESSION_LIB"

refuse() {
  printf 'notif-approve: REFUSED (%s)\n%s\n' "$1" "$2" >&2
  printf 'Approving a notification is a deliberate human action. There is no override flag and no config file that grants it.\n' >&2
  exit 77
}

case "${1:-}" in
  approve | revoke)
    declare -F session_is_human >/dev/null ||
      refuse "session-lib-missing" "Cannot verify the caller is human: $SESSION_LIB is absent."
    if ! reason="$(session_is_human)"; then
      refuse "$reason" "This machine classifies the caller as an agent runtime, not a human at a terminal."
    fi
    ;;
esac

exec python3 "$GATE" "$@"
