#!/bin/zsh
# safe-tccutil — wrapper around /usr/bin/tccutil that REFUSES the most
# destructive call shape: `tccutil reset <SERVICE>` (no bundle id).
#
# Why this exists:
#   2026-04-28 incident — running `tccutil reset Accessibility` (no bundle)
#   wiped every app's Accessibility grant on the machine. The user's mouse
#   enhancer, keyboard remapping, window manager, clipboard tool, and
#   remote-desktop tooling all became inert at once. There is NO recovery
#   API: each app must be re-authorized one by one in System Settings,
#   each touch requiring the macOS login password.
#
#   The mistake was easy to make: tccutil's CLI accepts `reset <SERVICE>`
#   without complaint and silently performs a subject-wide nuke. There is
#   no confirmation prompt and no "are you sure?" — Apple's CLI assumes
#   you know what you are doing.
#
#   This wrapper makes that mistake impossible without a typed override.
#
# Behavior:
#   * Pass-through for all `tccutil` invocations EXCEPT `reset <SERVICE>`
#     without a bundle id.
#   * Refuses subject-wide resets with a loud explanation + recovery
#     guidance.
#   * Honors `--i-know` as an explicit "yes I really want subject-wide"
#     escape hatch (will still print a warning + 3-second pause before
#     executing).
#
# Usage:
#   safe-tccutil reset Accessibility com.example.app   # OK, single app
#   safe-tccutil reset Accessibility                   # REFUSED
#   safe-tccutil reset Accessibility --i-know          # OK after warning
#   safe-tccutil <anything else>                       # transparent
#
# Recommend: alias tccutil=/Users/AI/HelperAI/bin/safe-tccutil
#            (in your shell rc) so accidental keystrokes go through here.

set -euo pipefail

usage() {
  awk 'NR == 1 { next } /^set -/ { exit } { sub(/^# ?/, ""); print }' "${(%):-%x}"
}

case "${1:-}" in
  -h|--help|help)
    usage
    exit 0
    ;;
esac

REAL=/usr/bin/tccutil
if [[ ! -x "$REAL" ]]; then
  echo "safe-tccutil: /usr/bin/tccutil not found" >&2
  exit 127
fi

# Pass-through if first arg isn't 'reset'
if [[ "${1:-}" != "reset" ]]; then
  exec "$REAL" "$@"
fi

# Now we know it's a reset call. Parse:
#   tccutil reset <SERVICE> [<BUNDLE_ID>] [--i-know]
shift  # consume 'reset'
service="${1:-}"
shift || true

bundle=""
force=false
for a in "$@"; do
  case "$a" in
    --i-know|--force) force=true ;;
    -*) ;;  # ignore other flags
    *)  [[ -z "$bundle" ]] && bundle="$a" ;;
  esac
done

if [[ -z "$service" ]]; then
  echo "safe-tccutil: 'reset' requires a service argument (e.g. Accessibility)" >&2
  exit 2
fi

# A subject-wide reset is `reset <SERVICE>` with NO bundle id.
if [[ -z "$bundle" ]]; then
  if ! $force; then
    cat >&2 <<EOF
═══════════════════════════════════════════════════════════════════
  safe-tccutil  REFUSED  subject-wide reset

    tccutil reset $service       ← wipes EVERY app's $service grant
═══════════════════════════════════════════════════════════════════

Why this is blocked:
  • subject-wide TCC reset is IRREVERSIBLE; no API or command can write
    "previously authorized" grants back into the database
  • each affected app must be re-authorized manually in System Settings,
    re-typing the macOS login password every time
  • on 2026-04-28 a single accidental subject-wide reset on this
    machine broke the user's mouse / keyboard / window manager /
    clipboard / remote-desktop and required ~30 minutes of manual
    recovery

If you truly mean to wipe a single app's grant:
    safe-tccutil reset $service <bundle.id>

If you truly mean a subject-wide reset (very rare; ask first):
    safe-tccutil reset $service --i-know

To inspect what is currently granted before deciding:
    sqlite3 "\$HOME/Library/Application Support/com.apple.TCC/TCC.db" \\
      "SELECT client, auth_value FROM access \\
       WHERE service='kTCCService$service' ORDER BY last_modified DESC;"

(See HelperAI bin/check-accessibility-status for a friendlier view.)
EOF
    exit 2
  fi

  # User typed --i-know. Print a final 3-second-cancel warning.
  echo "" >&2
  echo "safe-tccutil: about to do SUBJECT-WIDE reset of $service" >&2
  echo "             every app will lose its grant; you have 3 seconds to ^C…" >&2
  for n in 3 2 1; do
    printf "  …%s\n" "$n" >&2
    sleep 1
  done
  exec "$REAL" reset "$service"
fi

# Targeted reset: pass through.
exec "$REAL" reset "$service" "$bundle"
