#!/bin/bash
# Rezt companion installer (macOS). Review it first:
#   curl -fsSL https://rezt.dev/install.sh
set -euo pipefail

SENTINEL_WORK=""
sentinel_cleanup() { if [ -n "$SENTINEL_WORK" ]; then rm -rf "$SENTINEL_WORK"; fi; }

sentinel_install() {
  local server=https://rezt.dev
  local code=""
  local agent=""
  local argument
  for argument in "$@"; do
    case "$argument" in
      --code=*) code="${argument#--code=}" ;;
      --agent=claude|--agent=codex|--agent=antigravity) agent="${argument#--agent=}" ;;
      *) echo "Usage: install.sh [--code=PAIRING_CODE] [--agent=claude|codex|antigravity]" >&2; return 2 ;;
    esac
  done
  if [ "$(uname -s)" != "Darwin" ]; then
    echo "Rezt currently supports macOS only." >&2; return 1
  fi
  if ! xcode-select -p >/dev/null 2>&1; then
    echo "Rezt uses Apple's /usr/bin/python3. Run: xcode-select --install" >&2
    echo "Then run this installer again." >&2; return 1
  fi
  local python=/usr/bin/python3
  SENTINEL_WORK="$(mktemp -d)"
  trap sentinel_cleanup EXIT
  local name
  for name in claude_usage_watcher.py sentinel_statusline.py sentinel_sync.py install_sentinel.py install_rezt.py rezt.py rezt_native.py rezt_mod.js agent_usage.py antigravity_statusline.py install_agents.py rezt_platform.py; do
    curl -fsSL "$server/companion/$name" -o "$SENTINEL_WORK/$name"
  done
  if [ -n "$agent" ]; then
    "$python" "$SENTINEL_WORK/install_sentinel.py" --python "$python" --agent "$agent"
  else
    "$python" "$SENTINEL_WORK/install_sentinel.py" --python "$python"
  fi
  if [ -n "$code" ]; then
    "$python" "$HOME/.local/share/claude-sentinel/sentinel_sync.py" connect --url "$server" "--code=$code" --background
    "$python" "$HOME/.local/share/claude-sentinel/install_sentinel.py" --next-steps
  else
    echo "Next: open $server, choose + Add device, and run the command shown there."
  fi
}

sentinel_install "$@"
