#!/bin/bash
# Cleanly remove Cybee from this Mac. Safe to run repeatedly. Requires root.
#   curl -sSf https://delete.cybee.dev | sudo sh
# Removes: the daemon, binaries, content, state (state.db + quarantine + tokens), the menu-bar
# app, logs, the control socket, and the pkg receipt. Only touches Cybee-owned paths.
# An admin is asked to keep their AI chats connected (default yes): they stay admin of their
# company from the chat. --all removes those too, also later, when Cybee itself is already gone:
#   curl -sSf https://delete.cybee.dev | sudo sh -s -- --all
set -u
[ "$(id -u)" = "0" ] || { echo "run with sudo:  sudo $0"; exit 1; }

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

ALL=0
for a in "$@"; do [ "$a" = "--all" ] && ALL=1; done

CONSOLE_USER="$(stat -f %Su /dev/console 2>/dev/null)"
USER_HOME=""
[ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ] && USER_HOME="$(dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory 2>/dev/null | awk '{print $2; exit}')"
IS_ADMIN=0
[ -n "$USER_HOME" ] && grep -q '^cyk_' "$USER_HOME/.config/cybee/admin_token" 2>/dev/null && IS_ADMIN=1
COMPANY="$(/usr/local/bin/cybee --json status 2>/dev/null | sed -n 's/.*"org_name": *"\([^"]*\)".*/\1/p' | head -1)"
[ -n "$COMPANY" ] || COMPANY="your company"
KEEP=0
if [ "$IS_ADMIN" = 1 ] && [ "$ALL" = 0 ]; then
  KEEP=1
  # The script itself arrives on stdin (curl | sh), so a person answers on the terminal.
  if [ -t 1 ] && [ -r /dev/tty ]; then
    printf 'Keep your AI chats connected to %s? You stay admin and can manage it from your chat. [Y/n] ' "$COMPANY"
    read -r ans < /dev/tty || ans=""
    case "$ans" in [nN]*) KEEP=0 ;; esac
  fi
fi

# Tell the backend first, while the agent still runs (best effort; an admin can also use the
# remove_device tool if the Mac is offline).
if [ -x /usr/local/bin/cybee ]; then
  echo "==> removing this device from its organization"
  /usr/local/bin/cybee unenroll 2>/dev/null || echo "    (backend not reachable — an admin can remove it with remove_device)"
fi

# -H so $HOME is the console user's (their assistant configs + Cybee tokens), not root's.
if [ -n "$USER_HOME" ]; then
  if [ "$KEEP" = 1 ] && [ -x /usr/local/bin/cybee ] && /usr/local/bin/cybee disconnect --help 2>/dev/null | grep -q keep-chats; then
    say "keeping your AI chats connected to $COMPANY"
    sudo -u "$CONSOLE_USER" -H /usr/local/bin/cybee disconnect --keep-chats 2>/dev/null || true
    sudo -u "$CONSOLE_USER" -H sh -c 'rm -f "$HOME/.config/cybee/join_token"' 2>/dev/null || true
  else
    KEEP=0
    # The admin key backup in the iCloud Keychain goes with the chats. Only the signed app can
    # reach that keychain group, so ask it while the bundle still exists, in the person's session.
    APPBIN=/Applications/Cybee.app/Contents/MacOS/Cybee
    if [ -x "$APPBIN" ]; then
      uid="$(id -u "$CONSOLE_USER" 2>/dev/null)"
      [ -n "$uid" ] && launchctl asuser "$uid" sudo -u "$CONSOLE_USER" -H "$APPBIN" --keychain-forget 2>/dev/null || true
    elif [ "$IS_ADMIN" = 1 ]; then
      echo "    (the iCloud Keychain backup of your admin key can only be removed while Cybee is installed;"
      echo "     to end that admin access instead, revoke the admin in your AI chat)"
    fi
    # The installed command, or the copy an earlier admin uninstall kept for Claude's bridge.
    CLI=/usr/local/bin/cybee
    [ -x "$CLI" ] || CLI="$USER_HOME/.config/cybee/bin/cybee"
    if [ -x "$CLI" ]; then
      say "disconnecting AI assistants"
      sudo -u "$CONSOLE_USER" -H "$CLI" disconnect 2>/dev/null || true
    fi
    sudo -u "$CONSOLE_USER" -H sh -c 'rm -rf "$HOME/.config/cybee"' 2>/dev/null || true
  fi
  # Take Cybee off the Login Items list (the app registered itself there on first launch); only the
  # app can, and only while it is still installed, inside the person's session. Apps from 0.3.79 on
  # answer the flag; an older app would simply open instead, so it is left alone.
  APPBIN=/Applications/Cybee.app/Contents/MacOS/Cybee
  if [ -x "$APPBIN" ] && [ -n "$(defaults read /Applications/Cybee.app/Contents/Info CFBundleShortVersionString 2>/dev/null | awk -F. '$1>0||$2>3||($2==3&&$3>=79)')" ]; then
    uid="$(id -u "$CONSOLE_USER" 2>/dev/null)"
    [ -n "$uid" ] && launchctl asuser "$uid" sudo -u "$CONSOLE_USER" -H "$APPBIN" --login-item-forget >/dev/null 2>&1 || true
  fi
fi

# Reversibility promise: revert any applied hardening profile to baseline while the daemon
# still runs — never leave a machine hardened with the manager gone.
prof="$(/usr/local/bin/cybee status 2>/dev/null | /usr/bin/awk -F: '/^security profile/ {gsub(/ /,"",$2); print $2}')"
case "$prof" in
  balanced*|fortress*)
    say "reverting hardening to baseline first ($prof is applied — this can take a few minutes)"
    /usr/local/bin/cybee cis apply essential 2>/dev/null || true
    ;;
esac

# Never leave a Mac isolated with the manager gone: lift pf isolation while the daemon is
# still there to do it (the state files live in /var/db/cybee, deleted below).
if [ -f /var/db/cybee/isolation.pf.conf ] || [ -f /var/db/cybee/isolation.pf-was-enabled ]; then
  say "removing network isolation first"
  /usr/local/bin/cybee unisolate 2>/dev/null || { /sbin/pfctl -F all 2>/dev/null; /sbin/pfctl -f /etc/pf.conf 2>/dev/null; } || true
fi

say "stopping the app + legacy daemon"
launchctl bootout system /Library/LaunchDaemons/ai.cybee.agent.plist 2>/dev/null || true
pkill -f 'Cybee.app'  2>/dev/null || true
pkill -f 'cybee-esd'  2>/dev/null || true

# The app's preferences (first-run window marks, dismissed threats) and its per-user data go too,
# for every account on this Mac. Run as each account (never root inside someone's home), and only
# now that the app has quit, so nothing writes them back. Apple's own permission lists (Full Disk
# Access, notifications) are not Cybee's to edit; the chat connections were handled above.
say "removing the app's preferences"
for home in /Users/*; do
  u="$(stat -f%Su "$home" 2>/dev/null || true)"
  [ -n "$u" ] && [ "$u" != "root" ] && [ -d "$home/Library" ] || continue
  sudo -u "$u" -H defaults delete ai.cybee.CybeeAiAgent.desktop >/dev/null 2>&1 || true
  sudo -u "$u" -H sh -c 'rm -rf "$HOME/Library/Preferences/ai.cybee.CybeeAiAgent.desktop.plist" \
    "$HOME/Library/Saved Application State/ai.cybee.CybeeAiAgent.desktop.savedState" \
    "$HOME/Library/Caches/ai.cybee.CybeeAiAgent.desktop" \
    "$HOME/Library/HTTPStorages/ai.cybee.CybeeAiAgent.desktop" \
    "$HOME/Library/HTTPStorages/ai.cybee.CybeeAiAgent.desktop.binarycookies" \
    "$HOME/Library/WebKit/ai.cybee.CybeeAiAgent.desktop"' 2>/dev/null || true
done

say "removing files"
rm -f  /Library/LaunchDaemons/ai.cybee.agent.plist
rm -f  /usr/local/bin/cybee-esd /usr/local/bin/cybee
rm -rf /usr/local/share/cybee
rm -rf /var/db/cybee                 # state.db, quarantine, tokens (enrolment)
rm -f  /var/run/cybee.sock
rm -f  /var/log/cybee.log /var/log/cybee.log.*
rm -rf /Applications/Cybee.app /Applications/CybeeMenuBar.app
rm -rf "/Library/Application Support/Cybee"   # CybeeES.app (the daemon bundle)

say "clearing package receipt"
pkgutil --forget ai.cybee.installer; pkgutil --forget ai.cybee.agent >/dev/null 2>&1 || true

# Product event (22 Oct 2026): how removals end, as a code. A kept admin key ties it to the company.
UN_ITEM=employee; [ "$IS_ADMIN" = 1 ] && { UN_ITEM=all; [ "$KEEP" = 1 ] && UN_ITEM=kept; }
UN_H=""
if [ "$UN_ITEM" = kept ] && [ -n "$USER_HOME" ] && UN_H="$(mktemp 2>/dev/null)"; then
  chmod 600 "$UN_H"
  printf 'Authorization: Bearer %s\n' "$(tr -d '[:space:]' < "$USER_HOME/.config/cybee/admin_token" 2>/dev/null)" > "$UN_H"
fi
curl -s -m 2 -o /dev/null -H 'content-type: application/json' ${UN_H:+-H "@$UN_H"} \
  -d "{\"name\":\"uninstall.finished\",\"item\":\"$UN_ITEM\",\"client\":\"uninstall.sh\"}" \
  https://api.cybee.dev/v1/events/script >/dev/null 2>&1 || true
[ -n "$UN_H" ] && rm -f "$UN_H"

echo
echo "Cybee removed. This does NOT delete the organization on the backend; the device simply stops reporting."
if [ "$KEEP" = 1 ]; then
  echo
  echo "Your AI chats stay connected to $COMPANY: you are still its admin."
  echo "  Install Cybee again any time and choose to rejoin $COMPANY."
  echo "  To remove the chat connections too:  curl -sSf https://delete.cybee.dev | sudo sh -s -- --all"
fi
