#!/usr/bin/env bash
# Remove ALL legacy AIOR/AICN TCC rows (ghost list entries) and reset com.aior.connect grants.
# Requires one administrator password prompt (osascript) — Apple does not expose − via API.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CANONICAL="${HOME}/Applications/AIOR CONNECT.app"
TCC_DB="${HOME}/Library/Application Support/com.apple.TCC/TCC.db"
USER_UID="$(id -u)"

note() { echo "==> $*"; }

note "stop AIOR CONNECT"
pkill -9 -x AIORConnectService 2>/dev/null || true
pkill -9 -x AIORCONNECT 2>/dev/null || true
pkill -f "AICN-service" 2>/dev/null || true
pkill -f "aiorconnect-agent" 2>/dev/null || true
pkill -f "AIOR CONNECT" 2>/dev/null || true
launchctl bootout "gui/${USER_UID}/com.aior.connect.agent" 2>/dev/null || true

note "remove disk artifacts that re-register ghost names"
bash "${ROOT}/scripts/clean-mac-aiorconnect-full.sh" --no-sudo 2>/dev/null || \
  bash "${ROOT}/scripts/clean-mac-aiorconnect-full.sh" || true
bash "${ROOT}/scripts/dedupe-mac-privacy.sh" --reset-tcc

purge_tcc_sql() {
  local db="$1"
  sqlite3 "$db" <<'SQL'
.headers on
.mode column
SELECT 'before' AS phase, service, client, auth_value FROM access
WHERE service IN ('kTCCServiceScreenCapture','kTCCServiceAccessibility')
  AND (
    lower(client) LIKE '%aicn%'
    OR lower(client) LIKE '%aiorconnect-agent%'
    OR lower(client) LIKE '%aiorconnect%'
    OR lower(client) LIKE '%aior%connect%'
    OR client IN ('com.aior.connect','com.aior.connect.agent')
  );
DELETE FROM access
WHERE service IN ('kTCCServiceScreenCapture','kTCCServiceAccessibility')
  AND (
    lower(client) LIKE '%aicn%'
    OR lower(client) LIKE '%aiorconnect-agent%'
    OR lower(client) LIKE '%aiorconnect%'
    OR lower(client) LIKE '%aior%connect%'
    OR client IN ('com.aior.connect','com.aior.connect.agent')
  );
SELECT changes() AS rows_deleted;
SQL
}

note "purge TCC database rows (admin password may be requested once)"
ESC_DB="${TCC_DB//\"/\\\"}"
PURGE_OUT=""
if PURGE_OUT="$(sqlite3 "$TCC_DB" "SELECT count(*) FROM access LIMIT 1;" 2>/dev/null)"; then
  purge_tcc_sql "$TCC_DB"
else
  echo "TCC.db locked — requesting administrator access..."
  PURGE_OUT="$(osascript 2>/dev/null <<APPLESCRIPT || true
do shell script "sqlite3 \\"${ESC_DB}\\" \\"DELETE FROM access WHERE service IN ('kTCCServiceScreenCapture','kTCCServiceAccessibility') AND (lower(client) LIKE '%aicn%' OR lower(client) LIKE '%aiorconnect-agent%' OR lower(client) LIKE '%aiorconnect%' OR lower(client) LIKE '%aior%connect%' OR client IN ('com.aior.connect','com.aior.connect.agent')); SELECT changes();\\"" with administrator privileges
APPLESCRIPT
)"
  echo "$PURGE_OUT"
fi

note "reset bundle TCC cache"
tccutil reset ScreenCapture com.aior.connect 2>/dev/null || true
tccutil reset Accessibility com.aior.connect 2>/dev/null || true
tccutil reset ScreenCapture com.aior.connect.agent 2>/dev/null || true
tccutil reset Accessibility com.aior.connect.agent 2>/dev/null || true

if [[ -d "$CANONICAL" ]]; then
  note "re-sign canonical app"
  bash "${ROOT}/scripts/sign-mac-installer.sh" "$CANONICAL"
  AGENT="${CANONICAL}/Contents/MacOS/AIORConnectService"
  DESKTOP="${CANONICAL}/Contents/MacOS/AIOR CONNECT"
  if [[ -x "$AGENT" ]]; then
    "$AGENT" -request-screen 2>/dev/null || true
    sleep 1
    "$AGENT" -request-accessibility 2>/dev/null || true
  fi
  if [[ -x "$DESKTOP" ]]; then
    # Launch desktop once so macOS registers the branded AIOR CONNECT row (not AICN-service).
    open -n "$CANONICAL" 2>/dev/null || true
    sleep 2
  fi
fi

open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" 2>/dev/null || true
sleep 1
open "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" 2>/dev/null || true

cat <<'MSG'

WIPE_MAC_TCC_AIOR_GHOSTS_OK

'tccutil reset' clears every com.aior.connect grant (all past builds). Legacy-named rows
(AICN-service / AIORConnectService / AIORCONNECT / aiorconnect-agent) are bare executables
in the SIP-protected system TCC database — Apple exposes no API to delete them, so:

In BOTH panes that opened:
  1. Select each legacy row (AICN-service / AIORConnectService / AIORCONNECT / aiorconnect-agent) → press −
  2. After installing the new version, in AIOR CONNECT tap "Request access" for Screen
     Recording AND Accessibility, then enable the AIOR CONNECT service row that appears in BOTH panes.

Note: Accessibility and Screen Recording are now granted to the SAME service binary, so one
grant per pane is enough. Then: AIOR CONNECT → Permissions → Refresh → Start agent.

MSG
