#!/bin/sh
# Cybee installer — one command, no account, no card.
#
#   curl -sSf https://get.cybee.dev | sh                       # new org (auto-named; rename later)
#   curl -sSf https://get.cybee.dev | sh -s -- --name "Acme"   # new org with a name
#   curl -sSf https://get.cybee.dev | sh -s -- --join <TOKEN>   # join an existing org (teammate)
#   curl -sSf https://get.cybee.dev | sh -s -- --admin <TOKEN>  # join AND manage the fleet (admin)
#   ... --join <TOKEN> --owner "Hekuran Doli"                   # label whose Mac this is
#
# With no --join, this creates a fresh organization for you and prints your admin token — save
# it; it is how you manage the fleet from your AI assistant. Read this script: https://get.cybee.dev
set -eu

BACKEND="https://api.cybee.dev"
CONTENT="https://content.cybee.dev"
MCP="https://mcp.cybee.dev/mcp"
# Product events (22 Oct 2026): the install's steps as codes (mode, refusal reason, final status),
# so a step that fails for many people shows up the same day. Never a name, a host name or a key in
# the body; a join or admin key goes only in the Authorization header, from a file, to tie the
# install to its company. Two seconds at most, and nothing here can stop or change the install.
INSTALL_ID="$(od -An -N8 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')"
T0="$(date +%s)"
EV_TOKEN=""
ev() {
  _b=$(printf '{"name":"%s","item":"%s","reason":"%s","outcome":"%s","client":"cybee.sh","ref":"%s","value":%s}' \
    "$1" "${2:-}" "${3:-}" "${4:-ok}" "$INSTALL_ID" "$(( $(date +%s) - T0 ))")
  if [ -n "$EV_TOKEN" ] && _h="$(mktemp 2>/dev/null)"; then
    chmod 600 "$_h"; printf 'Authorization: Bearer %s\n' "$EV_TOKEN" > "$_h"
    curl -s -m 2 -o /dev/null -H 'content-type: application/json' -H @"$_h" -d "$_b" "$BACKEND/v1/events/script" >/dev/null 2>&1 || true
    rm -f "$_h"
  else
    curl -s -m 2 -o /dev/null -H 'content-type: application/json' -d "$_b" "$BACKEND/v1/events/script" >/dev/null 2>&1 || true
  fi
}
DOCS_CONNECT="https://docs.cybee.dev/connect"  # TODO: real docs page
FORCE=0
JOIN=""
NAME=""
ORG_ID=""
OWNER=""
OWNER_EXPLICIT=0
ADMIN_TOKEN=""
JOIN_IS_ADMIN=0

while [ $# -gt 0 ]; do
  case "$1" in
    --join) JOIN="$2"; shift 2 ;;
    # An admin invitation: one token that both enrolls this Mac in the org and makes it an
    # admin console (assistants wired, token saved). The backend accepts an admin token for
    # enrollment because admin strictly outranks join.
    --admin) ADMIN_TOKEN="$2"; JOIN="$2"; JOIN_IS_ADMIN=1; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --owner) OWNER="$2"; OWNER_EXPLICIT=1; shift 2 ;;
    --backend) BACKEND="$2"; shift 2 ;;
    --force) FORCE=1; shift ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done

if [ "$(uname -s)" != "Darwin" ]; then
  ev install.refused "" not_macos refused
  echo "cybee: macOS only for now (Windows/Linux coming)." >&2; exit 1
fi
# Check the Mac before anything touches the backend, so an unsupported Mac never creates an org.
ARCH="$(uname -m)"
if [ "$ARCH" != "arm64" ]; then
  ev install.refused "" intel refused
  echo "Cybee supports Apple Silicon Macs only (this Mac is $ARCH)." >&2
  echo "Intel Macs are not supported." >&2
  exit 1
fi
OS_VER="$(sw_vers -productVersion 2>/dev/null)"
if [ "${OS_VER%%.*}" -lt 15 ] 2>/dev/null; then
  ev install.refused "macos${OS_VER%%.*}" macos_old refused
  echo "Cybee needs macOS 15 or newer (this Mac runs $OS_VER)." >&2
  echo "Update macOS in System Settings > General > Software Update, then run this again." >&2
  exit 1
fi

# If --owner wasn't given, default to the real name of the Mac's primary (console) user — what
# they typed at setup. --owner always overrides. Handles both the "RealName: X" and two-line
# forms of dscl output, and skips root (e.g. when run via sudo).
if [ -z "$OWNER" ]; then
  CONSOLE_USER="$(stat -f%Su /dev/console 2>/dev/null || true)"
  if [ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ]; then
    OWNER="$(dscl . -read /Users/"$CONSOLE_USER" RealName 2>/dev/null \
      | awk 'NR==1{sub(/^RealName: */,"");if($0!=""){print;exit}} NR==2{sub(/^[[:space:]]*/,"");print;exit}')"
  fi
fi

# Extract a prefixed token (cyk_/cyj_/cya_) from a JSON blob without needing jq.
extract() { printf '%s' "$1" | grep -oE "\"$2\":\"[^\"]+\"" | head -1 | sed -E "s/.*:\"([^\"]+)\"/\1/"; }

UPGRADE=0
INSTALL_OK=0
ORG_CREATED=0

# If this run CREATED an org but the install never completed, delete the org again — otherwise
# every failed install leaves an orphan organization whose tokens nobody ever saw. Guarded by
# ORG_CREATED: with --admin we hold an admin token for an EXISTING org, and a failed install
# must never delete someone else's organization.
cleanup_failed_org() {
  if [ "$INSTALL_OK" != 1 ] && [ "$ORG_CREATED" = "1" ] && [ -n "$ADMIN_TOKEN" ]; then
    DAUTH="$(mktemp)"; printf 'authorization: Bearer %s\n' "$ADMIN_TOKEN" > "$DAUTH"
    curl -fsS -X DELETE "$BACKEND/v1/org" -H @"$DAUTH" >/dev/null 2>&1 || true; rm -f "$DAUTH"
  fi
}
trap cleanup_failed_org EXIT

# The human whose config and AI assistants we set up. Under sudo, $HOME often stays the
# invoking user's — writing there as root leaves the person unable to read their own admin
# token, and `cybee connect` would wire root's (nonexistent) assistants with root's PATH.
CFG_USER="$(id -un)"
if [ "$(id -u)" = "0" ]; then
  CFG_USER="${SUDO_USER:-}"
  [ -n "$CFG_USER" ] && [ "$CFG_USER" != "root" ] || CFG_USER="$(stat -f%Su /dev/console 2>/dev/null || echo root)"
fi
CFG_HOME="$(dscl . -read "/Users/$CFG_USER" NFSHomeDirectory 2>/dev/null | awk '{print $2; exit}')"
[ -n "$CFG_HOME" ] || CFG_HOME="$HOME"
# Run a user-level command (cybee connect) as that human, not as root.
as_cfg_user() {
  if [ "$(id -u)" = "0" ] && [ "$CFG_USER" != "root" ]; then
    sudo -u "$CFG_USER" -H "$@"
  else
    "$@"
  fi
}
# Already enrolled? A plain re-run just reinstalls/upgrades the agent (organization unchanged).
# With --name or --join it would silently move this Mac into another org: refuse unless --force.
if [ -f /var/db/cybee/state.db ] && [ "$FORCE" != "1" ]; then
  if [ -n "$NAME" ] || [ -n "$JOIN" ]; then
    echo "cybee: this Mac is already enrolled in a Cybee organization." >&2
    echo "  'cybee status' shows it; 'sudo cybee uninstall' removes it." >&2
    echo "  To move this Mac to a different/new organization anyway: add --force" >&2
    echo "CYBEE_STATUS=already-enrolled"
    ev install.refused "" already_enrolled refused
    exit 5
  fi
  echo "==> Cybee is already enrolled on this Mac: reinstalling the agent (organization unchanged)"
  if [ "$OWNER_EXPLICIT" = "1" ]; then
    echo "    Note: --owner only applies when a Mac first enrols. To change who this Mac"
    echo "    belongs to, ask your AI assistant: \"set the owner of this Mac to <name>\""
    echo "    (no reinstall needed — --force would enrol it again as a second device)."
  fi
  UPGRADE=1
fi
MODE=new; [ -n "$JOIN" ] && MODE=join; [ "$JOIN_IS_ADMIN" = 1 ] && MODE=admin; [ "$UPGRADE" = 1 ] && MODE=upgrade
[ "$FORCE" = 1 ] && MODE="${MODE}_force"
EV_TOKEN="$JOIN"
ev install.started "$MODE" "macos${OS_VER%%.*}"
# A key an admin uninstall kept: offer to rejoin that company rather than silently creating a new
# one (which would also move the admin's kept chats away from it and lock them out).
REPLACE_CHATS=0
KEPT_KEY=""
if [ "$UPGRADE" = "0" ] && [ -z "$JOIN" ] && [ -f "$CFG_HOME/.config/cybee/admin_token" ]; then
  KEPT_KEY="$(tr -d '[:space:]' < "$CFG_HOME/.config/cybee/admin_token" 2>/dev/null || true)"
  case "$KEPT_KEY" in cyk_*) ;; *) KEPT_KEY="" ;; esac
fi
if [ -n "$KEPT_KEY" ]; then
  # The key goes to curl through a file, never on the command line (argv is visible to every local account).
  KAUTH="$(mktemp)"; printf 'authorization: Bearer %s\n' "$KEPT_KEY" > "$KAUTH"
  KRESP="$(curl -sS -w '\n%{http_code}' -H @"$KAUTH" "$BACKEND/v1/devices" 2>/dev/null || printf '\n000')"; rm -f "$KAUTH"
  KCODE="$(printf '%s' "$KRESP" | tail -n 1)"
  if [ "$KCODE" = "200" ]; then
    KCOMPANY="$(extract "$KRESP" org_name)"; [ -n "$KCOMPANY" ] || KCOMPANY="your company"
    KMACS="$(printf '%s' "$KRESP" | grep -o '"hostname"' | wc -l | tr -d ' ')"
    KCHOICE=rejoin
    if [ -t 1 ] && [ -r /dev/tty ]; then
      printf "You're an admin of %s (%s Macs). Rejoin %s, or create a new company? [R/n] " "$KCOMPANY" "$KMACS" "$KCOMPANY"
      read -r ans < /dev/tty || ans=""
      case "$ans" in
        [nN]*)
          printf 'Your AI chats on this Mac will switch to the new company, and you lose access to %s from them unless another admin invites you. Continue? [y/N] ' "$KCOMPANY"
          read -r ans2 < /dev/tty || ans2=""
          case "$ans2" in [yY]*) KCHOICE=new ;; esac
          ;;
      esac
    fi
    if [ "$KCHOICE" = "rejoin" ]; then
      echo "==> rejoining $KCOMPANY as admin"
      ADMIN_TOKEN="$KEPT_KEY"; JOIN="$KEPT_KEY"; JOIN_IS_ADMIN=1
    else
      REPLACE_CHATS=1
    fi
  elif [ "$KCODE" = "401" ]; then
    echo "==> the admin key saved on this Mac no longer works (revoked, or its company was closed): removing it"
    rm -f "$CFG_HOME/.config/cybee/admin_token" "$CFG_HOME/.config/cybee/org_id"
  else
    echo "cybee: could not reach Cybee to check the admin key saved on this Mac." >&2
    echo "  Check the internet connection and run this again." >&2
    exit 3
  fi
fi

# No key anywhere on this Mac yet the admin's key may still be in their iCloud Keychain (a new or
# wiped Mac on the same Apple ID). Only the installed, signed Cybee app can read it, so the company
# is decided INSIDE the privileged step, after the package is installed: the daemon starts without
# a join token and waits; the step asks the app, decides (rejoin, or a new company), writes the
# token and restarts the daemon. With --name a new company was asked for: no keychain question.
# Whether a person can be asked on the terminal (the root step reads /dev/tty itself).
ASK=0; [ -t 1 ] && [ -r /dev/tty ] && ASK=1

PKG_URL="$CONTENT/mac/cybee-$ARCH.pkg"
TMP="$(mktemp -d)"; PKG="$TMP/cybee.pkg"

echo "==> downloading Cybee ($ARCH)"
if [ -n "${CYBEE_PKG_FILE:-}" ]; then
  # Testing a build before it is released: a local package (still checked for Apple's notarization below).
  cp "$CYBEE_PKG_FILE" "$PKG"
else
  curl -fsSL "$PKG_URL" -o "$PKG" || { ev install.refused "" download refused; echo "cybee: the download failed. Check the internet connection and run this again." >&2; exit 3; }
fi

echo "==> verifying Apple signature & notarization"
spctl -a -vv -t install "$PKG" 2>&1 | grep -qi accepted || { ev install.refused "" not_notarized refused; echo "cybee: package not notarized — aborting." >&2; exit 3; }
# Notarized is not enough: it must be OUR package (Cybee's Developer ID team), not anyone's.
pkgutil --check-signature "$PKG" 2>/dev/null | grep -q "Developer ID Installer: .*(D7UBTQ5RA2)" || { ev install.refused "" not_signed refused; echo "cybee: package is not signed by Cybee — aborting." >&2; exit 3; }

# One privileged step: stash enrolment inputs for the agent, then run the installer. Root path
# chosen by context — already root; sudo (terminal, may prompt); otherwise macOS's own
# administrator dialog, so an AI assistant's shell (no TTY for sudo) can still install while the
# person types the password into the system dialog.
# The root script is a QUOTED heredoc: nothing from this shell is interpolated into it. The
# values it needs (join token, backend, owner, flags) travel as environment variables, so an
# owner name like O'Brien — or anything else — can never break out of the root shell.
shq() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
ENVF="$TMP/install-env.sh"
{
  printf 'CYBEE_UPGRADE=%s\n' "$(shq "$UPGRADE")"
  printf 'CYBEE_FORCE=%s\n'   "$(shq "$FORCE")"
  printf 'CYBEE_JOIN=%s\n'    "$(shq "$JOIN")"
  printf 'CYBEE_BACKEND=%s\n' "$(shq "$BACKEND")"
  printf 'CYBEE_OWNER=%s\n'   "$(shq "$OWNER")"
  printf 'CYBEE_PKG=%s\n'     "$(shq "$PKG")"
  printf 'CYBEE_NAME=%s\n'    "$(shq "$NAME")"
  printf 'CYBEE_CFG_USER=%s\n' "$(shq "$CFG_USER")"
  printf 'CYBEE_ASK=%s\n'     "$(shq "$ASK")"
  printf 'CYBEE_RESULT=%s\n'  "$(shq "$TMP/decision.sh")"
} > "$ENVF"
chmod 600 "$ENVF"
PRIV="$TMP/install-root.sh"
cat > "$PRIV" <<'EOS'
#!/bin/sh
set -e
. "$(dirname "$0")/install-env.sh"
mkdir -p /var/db/cybee
chmod 700 /var/db/cybee
if [ "$CYBEE_UPGRADE" = "0" ]; then
  if [ -n "$CYBEE_JOIN" ]; then printf '%s' "$CYBEE_JOIN" > /var/db/cybee/join_token; chmod 600 /var/db/cybee/join_token; fi
  printf '%s' "$CYBEE_BACKEND" > /var/db/cybee/backend_url
  if [ -n "$CYBEE_OWNER" ]; then printf '%s' "$CYBEE_OWNER" > /var/db/cybee/owner; fi
fi
if [ "$CYBEE_FORCE" = "1" ] && [ -f /var/db/cybee/state.db ]; then
  # Moving to another organization (or re-enrolling this one). RETIRE THE OLD REGISTRATION
  # FIRST: the agent tells the backend it is going away, so the previous device row is marked
  # removed instead of lingering as a ghost Mac in the fleet. Without this, every --force
  # re-run left a duplicate entry for the same physical machine that nothing would ever
  # clean up. Best-effort: an offline or already-broken enrollment must not block a reinstall.
  if [ -x /usr/local/bin/cybee ]; then
    /usr/local/bin/cybee unenroll >/dev/null 2>&1 || true
  fi
  # Then drop the local enrollment so the agent re-enrols with the new token (alerts,
  # quarantine index and CIS baseline are kept).
  /usr/bin/sqlite3 /var/db/cybee/state.db "DELETE FROM agent_config WHERE key IN ('agent_token','device_id','org_id','backend_url')" || true
  # The previous enrolment's join token survives upgrades; left in place it would pre-empt the
  # company decision below and silently re-enrol the Mac where it was. Only when none was given now.
  [ -n "$CYBEE_JOIN" ] || rm -f /var/db/cybee/join_token
fi
# The package was checked by the person's shell in the person's temp folder. Root takes its own
# copy into a root-only folder and checks it again (notarized, AND signed by Cybee's team) before
# the installer sees it, so nothing that happened to the temp folder in between can matter.
RPKG=/var/db/cybee/install.pkg
rm -f "$RPKG"; cp "$CYBEE_PKG" "$RPKG"; chmod 600 "$RPKG"
spctl -a -vv -t install "$RPKG" 2>&1 | grep -qi accepted || { echo "cybee: package not notarized — aborting." >&2; rm -f "$RPKG"; exit 3; }
pkgutil --check-signature "$RPKG" 2>/dev/null | grep -q "Developer ID Installer: .*(D7UBTQ5RA2)" || { echo "cybee: package is not signed by Cybee — aborting." >&2; rm -f "$RPKG"; exit 3; }
# Every install starts over: clear the first-run window's "already shown" mark for the person
# installing, so the window opens again after this install too. The agent's own self-update never
# comes through this script, so an update stays silent.
if [ -n "$CYBEE_CFG_USER" ] && [ "$CYBEE_CFG_USER" != "root" ]; then
  for k in welcomeDone welcomeDoneDevice; do
    sudo -u "$CYBEE_CFG_USER" -H defaults delete ai.cybee.CybeeAiAgent.desktop "$k" >/dev/null 2>&1 || true
  done
fi
/usr/sbin/installer -pkg "$RPKG" -target /
rm -f "$RPKG"

# Does this Mac still need a company? No device credentials and no join token: a fresh install
# that was told nothing, or a re-run after a half-finished one. An enrolled Mac is left alone.
has_creds=0
if [ -f /var/db/cybee/state.db ] && [ -n "$(/usr/bin/sqlite3 /var/db/cybee/state.db "SELECT value FROM agent_config WHERE key='device_id'" 2>/dev/null)" ]; then has_creds=1; fi
if [ "$has_creds" = 0 ] && [ ! -s /var/db/cybee/join_token ]; then
  ext() { printf '%s' "$1" | grep -oE "\"$2\":\"[^\"]*\"" | head -1 | sed -E 's/.*:"([^"]*)"/\1/'; }
  q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
  JOIN=""; ADMIN=""; ORG_ID=""; CREATED=0; IS_ADMIN=0; COMPANY=""
  APPBIN=/Applications/Cybee.app/Contents/MacOS/Cybee
  uid="$(id -u "$CYBEE_CFG_USER" 2>/dev/null || echo 0)"
  if [ -z "$CYBEE_NAME" ] && [ -x "$APPBIN" ] && [ -n "$CYBEE_CFG_USER" ] && [ "$CYBEE_CFG_USER" != "root" ] && [ "$uid" != "0" ]; then
    # Ask the app for the iCloud Keychain backup, in the person's own session, bounded in time.
    OUTF="$(dirname "$0")/lookup.json"
    # A done marker, not kill -0: a finished child is reaped at shell-specific times, and under
    # set -e a failing kill would end this step before the token is written.
    ( launchctl asuser "$uid" sudo -u "$CYBEE_CFG_USER" -H "$APPBIN" --keychain-lookup > "$OUTF" 2>/dev/null; : > "$OUTF.done" ) & lpid=$!
    i=0; while [ ! -f "$OUTF.done" ] && [ "$i" -lt 60 ]; do sleep 0.5; i=$((i+1)); done
    [ -f "$OUTF.done" ] || kill "$lpid" 2>/dev/null || true
    wait "$lpid" 2>/dev/null || true
    LOOK="$(cat "$OUTF" 2>/dev/null || echo '{}')"
    KEY="$(ext "$LOOK" key)"
    case "$KEY" in cyk_*) ;; *) KEY="" ;; esac
    if [ -n "$KEY" ]; then
      COMPANY="$(ext "$LOOK" org_name)"; [ -n "$COMPANY" ] || COMPANY="your company"
      MACS="$(printf '%s' "$LOOK" | grep -oE '"macs":[0-9]+' | grep -oE '[0-9]+' || echo 0)"
      CHOICE=rejoin
      if [ "$CYBEE_ASK" = "1" ] && [ -r /dev/tty ]; then
        printf "You're an admin of %s (%s Macs), from your iCloud Keychain. Rejoin %s, or create a new company? [R/n] " "$COMPANY" "$MACS" "$COMPANY" > /dev/tty
        read -r ans < /dev/tty || ans=""
        case "$ans" in [nN]*) CHOICE=new ;; esac
      fi
      if [ "$CHOICE" = "rejoin" ]; then
        echo "==> rejoining $COMPANY as admin (your key, from your iCloud Keychain)"
        JOIN="$KEY"; ADMIN="$KEY"; IS_ADMIN=1; ORG_ID="$(ext "$LOOK" org_id)"
      fi
    fi
  fi
  if [ -z "$JOIN" ]; then
    # New organization. Auto-named unless --name given; you can rename later.
    NAME="$CYBEE_NAME"; [ -n "$NAME" ] || NAME="New org $(date +%Y-%m-%d)"
    echo "==> creating your Cybee organization"
    # A quote or backslash in the name must not break (or extend) the JSON body.
    JNAME="$(printf '%s' "$NAME" | tr -d '\000-\037' | sed 's/\\/\\\\/g; s/"/\\"/g')"
    RESP="$(curl -fsS -X POST "$CYBEE_BACKEND/v1/org" -H 'content-type: application/json' -d "{\"name\":\"$JNAME\"}")" || RESP=""
    ADMIN="$(ext "$RESP" admin_token)"; JOIN="$(ext "$RESP" join_token)"; ORG_ID="$(ext "$RESP" org_id)"
    if [ -z "$JOIN" ] || [ -z "$ADMIN" ]; then
      echo "cybee: Cybee is installed, but your company could not be created (no internet?). Run this again." >&2
      exit 3
    fi
    CREATED=1
  fi
  printf '%s' "$JOIN" > /var/db/cybee/join_token; chmod 600 /var/db/cybee/join_token
  # The daemon started without a token and waited: restart it, it enrols now.
  launchctl kickstart -k system/ai.cybee.agent 2>/dev/null || true
  # Hand the decision back to the outer script (the person's, unprivileged).
  umask 077
  {
    printf 'ADMIN_TOKEN=%s\n' "$(q "$ADMIN")"
    printf 'JOIN=%s\n' "$(q "$JOIN")"
    printf 'ORG_ID=%s\n' "$(q "$ORG_ID")"
    printf 'ORG_CREATED=%s\n' "$CREATED"
    printf 'JOIN_IS_ADMIN=%s\n' "$IS_ADMIN"
    printf 'KCOMPANY=%s\n' "$(q "$COMPANY")"
  } > "$CYBEE_RESULT"
  chown "$CYBEE_CFG_USER" "$CYBEE_RESULT" 2>/dev/null || true
fi
EOS
chmod 700 "$PRIV"
if [ "$(id -u)" = "0" ]; then
  echo "==> installing"
  /bin/sh "$PRIV"
elif [ -t 1 ] || sudo -n true 2>/dev/null; then   # a real terminal: sudo can prompt on /dev/tty
  echo "==> installing (you may be asked for your password)"
  sudo /bin/sh "$PRIV"
else
  echo "==> installing — macOS will ask for this Mac's password in a dialog"
  /usr/bin/osascript -e "do shell script \"/bin/sh '$PRIV'\" with administrator privileges with prompt \"Cybee needs your password to install its security extension.\"" >/dev/null \
    || {
      ev install.refused "" not_authorized refused
      echo "cybee: installation was not authorized." >&2
      echo "  If no password dialog appeared (SSH or no GUI session), re-run with sudo:" >&2
      echo "    curl -sSf https://get.cybee.dev | sudo sh" >&2
      rm -rf "$TMP"; exit 4
    }
fi
# The company decision made inside the privileged step (a keychain rejoin, or a new company).
if [ -f "$TMP/decision.sh" ]; then . "$TMP/decision.sh"; fi
rm -rf "$TMP"
INSTALL_OK=1

# 0.3.73+ opens the Cybee window right after install: it walks through Full Disk Access and shows the
# owner which AI chats are connected. Only when this person is the one at the screen; over SSH the
# terminal does it all.
WINDOW=0
if [ -d /Applications/Cybee.app ] && [ "$(stat -f%Su /dev/console 2>/dev/null)" = "$CFG_USER" ] \
  && [ -n "$(defaults read /Applications/Cybee.app/Contents/Info CFBundleShortVersionString 2>/dev/null | awk -F. '$1>0||$2>3||($2==3&&$3>=73)')" ]; then
  WINDOW=1
fi

# Keep the tokens where the person (and their assistant) can find them again: the admin token is
# shown once by the backend, and terminal output scrolls away.
if [ "$UPGRADE" = "1" ]; then
  echo
  echo "==> Cybee reinstalled. Check:  cybee status"
  echo "    If status shows real-time protection waiting, grant Full Disk Access:  cybee grant-fda"
  # Refresh the MCP token in any already-connected assistant. `cybee connect` reads the saved
  # ~/.config/cybee/admin_token itself — we never put the token on the command line (argv is
  # world-readable via ps).
  if [ -f "$CFG_HOME/.config/cybee/admin_token" ]; then
    as_cfg_user /usr/local/bin/cybee connect --refresh --url "$MCP" 2>/dev/null || true
  fi
  [ -f "$CFG_HOME/.config/cybee/admin_token" ] && EV_TOKEN="$(tr -d '[:space:]' < "$CFG_HOME/.config/cybee/admin_token" 2>/dev/null || true)"
  ev install.finished upgraded
  echo "CYBEE_STATUS=upgraded"; exit 0
fi
CFG="$CFG_HOME/.config/cybee"
# Under sudo this runs as root inside the person's home: a link planted at any of these places
# would send root's write somewhere else. Links are refused; the key files are recreated.
for p in "$CFG_HOME/.config" "$CFG"; do
  if [ -L "$p" ]; then echo "cybee: $p is a symbolic link — refusing to write there. Remove it and run again." >&2; echo "CYBEE_STATUS=failed"; exit 5; fi
done
mkdir -p "$CFG"; chmod 700 "$CFG"
for f in admin_token org_id join_token; do [ -L "$CFG/$f" ] && rm -f "$CFG/$f"; done
if [ -n "$ADMIN_TOKEN" ]; then
  # This machine created the org: it is the admin. Save the admin token and the org it belongs
  # to, so the console can confirm the token matches this device's org before showing fleet.
  printf '%s\n' "$ADMIN_TOKEN" > "$CFG/admin_token"; chmod 600 "$CFG/admin_token"
  [ -n "$ORG_ID" ] && { printf '%s\n' "$ORG_ID" > "$CFG/org_id"; chmod 600 "$CFG/org_id"; }
else
  # Joined an existing org as a member — not an admin. Remove any stale admin token/org left
  # from a previous org on this machine so the console never shows fleet views it can't use.
  rm -f "$CFG/admin_token" "$CFG/org_id"
fi
# With --admin, $JOIN holds the ADMIN token (it enrolled this Mac) — it must never be stored
# or shown as a join token, which is a lower-privilege credential meant for sharing.
if [ "$JOIN_IS_ADMIN" = "0" ]; then
  printf '%s\n' "$JOIN" > "$CFG/join_token"; chmod 600 "$CFG/join_token"
fi
# Under sudo these files were written by root into the person's home — hand them back,
# or the customer gets "Permission denied" reading their own admin token.
if [ "$(id -u)" = "0" ] && [ "$CFG_USER" != "root" ]; then
  chown -R "$CFG_USER" "$CFG" 2>/dev/null || true
  # mkdir -p may have created ~/.config itself as root.
  [ "$(stat -f%Su "$CFG_HOME/.config" 2>/dev/null)" = "root" ] && chown "$CFG_USER" "$CFG_HOME/.config" 2>/dev/null || true
fi

# Presentation. Colors and the interactive "wait for Full Disk Access" step apply only on a real
# terminal; a non-TTY caller (an AI assistant running the script) gets a plain machine-readable
# summary instead and never blocks.
TTY=0; [ -t 1 ] && TTY=1
if [ "$TTY" = 1 ]; then
  B=$(printf '\033[1m'); DIM=$(printf '\033[2m'); G=$(printf '\033[32m')
  Y=$(printf '\033[33m'); C=$(printf '\033[36m'); RS=$(printf '\033[0m')
else
  B=; DIM=; G=; Y=; C=; RS=
fi
BAR="${C}│${RS}"
rule() { printf '%s\n' "${DIM}────────────────────────────────────────────────────────────${RS}"; }

echo
rule
printf '  %s  %sCybee is installed%s\n' "🐝" "${G}${B}" "${RS}"
rule

# --- Admin token (save it) ---------------------------------------------------
if [ -n "$ADMIN_TOKEN" ] && [ "$JOIN_IS_ADMIN" = "1" ]; then
  # Invited admin: they already hold the token (it was in the invite), so don't re-present it
  # as a secret to write down — just say what they now have.
  echo
  echo "  ${B}You are an admin of this fleet${RS} ${DIM}(token saved to $CFG/admin_token)${RS}"
  echo "  ${DIM}This Mac is protected AND can manage the fleet from your AI chat.${RS}"
elif [ -n "$ADMIN_TOKEN" ]; then
  echo
  echo "  ${B}Your admin token${RS} ${DIM}(also saved to $CFG/admin_token)${RS}"
  echo "  ${BAR} ${Y}${ADMIN_TOKEN}${RS}"
  echo "  ${DIM}Manages your whole fleet from an AI chat. Save it — shown once.${RS}"
  echo "  ${DIM}Need a co-admin later? Ask your AI assistant: \"invite an admin\".${RS}"
fi

# --- Wire up local AI assistants (admin only) --------------------------------
# Scan for Claude, Claude Code, Codex and Cursor and point them at Cybee's MCP with the admin token.
# Re-running the installer refreshes the token in whatever is already configured.
if [ -n "$ADMIN_TOKEN" ]; then
  echo
  echo "  ${B}Connecting your AI assistants${RS}"
  # Token via env, never argv (ps-readable). `cybee connect` also falls back to the saved file.
  # --replace only after the person chose a new company over the one their kept chats belong to.
  CONNECT_REPLACE=""; [ "$REPLACE_CHATS" = 1 ] && CONNECT_REPLACE="--replace"
  as_cfg_user env CYBEE_ADMIN_TOKEN="$ADMIN_TOKEN" /usr/local/bin/cybee connect --url "$MCP" $CONNECT_REPLACE 2>/dev/null | while IFS= read -r ln; do
    echo "  ${BAR} $ln"
  done
fi

# --- The one permission: Full Disk Access ------------------------------------
echo
echo "  ${Y}${B}Last step — turn on Full Disk Access${RS}"
echo "  ${BAR} Cybee's threat engine (Endpoint Security) is gated by macOS behind"
echo "  ${BAR} Full Disk Access. Until you switch it on, real-time protection can't run."
echo "  ${BAR}"
if [ "$WINDOW" = 1 ]; then
  # 0.3.73+: the Cybee window that just opened walks through the switch and shows a first look.
  echo "  ${BAR} Finish in the ${B}Cybee${RS} window: it opens System Settings at the right place"
  echo "  ${BAR} and shows what to turn on (${B}Cybee${RS} in the list)."
else
  echo "  ${BAR} A ${B}System Settings${RS} window is opening at Full Disk Access."
  echo "  ${BAR} Find ${B}Cybee${RS} in the list and switch it ${G}${B}on${RS} — that's the only step."
  # Give the message a beat, then open the Full Disk Access pane.
  ( sleep 2; open "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles" >/dev/null 2>&1 ) &
fi

FDA_STATE=later
if [ "$TTY" = 1 ]; then
  echo
  printf '  %sWaiting for you to enable it%s ' "${DIM}" "${RS}"
  granted=0; i=0
  while [ "$i" -lt 150 ]; do   # ~5 minutes at 2s
    if /usr/local/bin/cybee --json status 2>/dev/null | grep -qE '"realtime_protection":[[:space:]]*true'; then
      granted=1; break
    fi
    printf '.'; sleep 2; i=$((i+1))
  done
  echo
  if [ "$granted" = 1 ]; then
    FDA_STATE=granted
    echo "  ${G}${B}✓ Protection is ON.${RS} Cybee is watching this Mac in real time."
  else
    FDA_STATE=timeout
    echo "  ${Y}Not enabled yet.${RS} Finish anytime: enable Cybee in Full Disk Access,"
    echo "  then run  ${C}cybee grant-fda${RS}  or check  ${C}cybee status${RS}."
  fi
else
  echo "  (Grant it later with: cybee grant-fda)"
fi

# --- Footer ------------------------------------------------------------------
echo
if [ "$JOIN_IS_ADMIN" = "0" ]; then
  echo "  ${DIM}Add a teammate's Mac:${RS}  ${C}curl -sSf https://get.cybee.dev | sh -s -- --join $JOIN${RS}"
else
  echo "  ${DIM}Add a teammate's Mac:${RS}  ask your AI assistant — \"invite a teammate\""
fi
echo "  ${DIM}Remove any time:${RS}      ${C}sudo cybee uninstall${RS}"
echo

EV_TOKEN="${ADMIN_TOKEN:-$JOIN}"
ev install.finished installed "$FDA_STATE"

# Machine-readable summary — only for a non-TTY caller (an assistant parsing output).
if [ "$TTY" = 0 ]; then
  echo "CYBEE_STATUS=installed"
  [ -n "$ADMIN_TOKEN" ] && echo "CYBEE_ADMIN_TOKEN=$ADMIN_TOKEN"
  [ "$JOIN_IS_ADMIN" = "0" ] && echo "CYBEE_JOIN_TOKEN=$JOIN"
  echo "CYBEE_MCP_URL=$MCP"
fi
