#!/usr/bin/env bash
# setup-claude-sandbox.sh
# One-time setup of Docker Sandboxes (sbx) on a Mac, for testing Claude Code
# plugins in a throwaway sandbox instead of on your real machine.
#
# Guide: https://blog.redefinedbyai.tech/posts/claude-plugin-sandbox.html
# Needs: an Apple silicon Mac (M1 or newer) on macOS 14 or later, and a free Docker account.
# Safe to run again: every step that is already done is skipped.
#
#   bash setup-claude-sandbox.sh              run the setup
#   DRY_RUN=1 bash setup-claude-sandbox.sh    only print what it would do
#   LAB_DIR=~/my-lab bash setup-claude-sandbox.sh   use another lab folder
set -euo pipefail

LAB_DIR="${LAB_DIR:-$HOME/claude-lab}"
DRY_RUN="${DRY_RUN:-0}"

say() { printf '\n\033[1m==> %s\033[0m\n' "$*"; }
run() { if [ "$DRY_RUN" = 1 ]; then printf '   [dry run] %s\n' "$*"; else "$@"; fi; }
die() { printf '\nStopped: %s\n' "$*" >&2; exit 1; }
# sbx diagnose prints JSON checks as  "name": "...",  then  "status": "...".
check_passes() { sbx diagnose --json 2>/dev/null | grep -A1 "\"name\": \"$1\"" | grep -q '"status": "pass"'; }

# 1. This Mac
say "Checking this Mac"
[ "$(uname -s)" = Darwin ] || die "this script is for macOS. The Windows and Linux steps are in the guide."
[ "$(uname -m)" = arm64 ] || die "Docker Sandboxes needs an Apple silicon Mac (M1 or newer)."
macos="$(sw_vers -productVersion)"
[ "${macos%%.*}" -ge 14 ] || die "Docker Sandboxes needs macOS 14 (Sonoma) or later. This Mac has $macos."
echo "   macOS $macos on Apple silicon: OK"

# 2. Homebrew
say "Homebrew"
if ! command -v brew >/dev/null 2>&1 && [ -x /opt/homebrew/bin/brew ]; then
  eval "$(/opt/homebrew/bin/brew shellenv)"
fi
if command -v brew >/dev/null 2>&1; then
  echo "   already installed: $(brew --version | head -1)"
else
  echo "   Installing Homebrew. It asks for your Mac password and to press Return."
  hb_url=https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh
  if [ "$DRY_RUN" = 1 ]; then
    echo "   [dry run] install Homebrew from $hb_url"
  else
    /bin/bash -c "$(curl -fsSL "$hb_url")"
    eval "$(/opt/homebrew/bin/brew shellenv)"
    # So brew and sbx also work in new Terminal windows.
    grep -qs 'brew shellenv' "$HOME/.zprofile" || echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$HOME/.zprofile"
  fi
fi

# 3. The sbx command
say "Docker Sandboxes (sbx)"
if command -v sbx >/dev/null 2>&1; then
  echo "   already installed: $(sbx version | head -1)"
else
  # Newer Homebrew only installs from third-party taps you have trusted.
  # Older Homebrew has no "trust" command and doesn't need it.
  run brew trust docker/tap || true
  run brew install docker/tap/sbx
fi

# 4. Over SSH the Mac's Keychain is locked, and sbx keeps your Docker sign-in there.
if [ -n "${SSH_CONNECTION:-}" ]; then
  say "Unlocking the Keychain (you are connected over SSH)"
  echo "   Type this Mac's login password. Nothing shows while you type."
  run security unlock-keychain "$HOME/Library/Keychains/login.keychain-db"
fi

# 5. Docker sign-in
say "Docker sign-in"
if check_passes "Authentication"; then
  echo "   already signed in"
else
  echo "   Sign in with your Docker account in the browser that opens (sign up there if you have none)."
  run sbx login
fi

# 6. Network rules for every sandbox
say "Network policy"
if check_passes "Global network policy"; then
  echo "   already set"
else
  echo "   Balanced: AI services, GitHub and package registries are allowed, everything else is blocked."
  run sbx policy init balanced
fi

# 7. Over SSH, restart the sbx background service in the Mac's own desktop session.
#    A service started from SSH cannot read the sign-in from the Keychain.
if [ -n "${SSH_CONNECTION:-}" ]; then
  say "Restarting the sbx service on the Mac's desktop"
  restart="$HOME/sbx-daemon-restart.command"
  run sh -c "printf '#!/bin/zsh -l\nsbx daemon restart\n' > '$restart' && chmod +x '$restart' && open '$restart'"
  echo "   A Terminal window opens on the Mac's screen and restarts it."
  echo "   After every restart of that Mac, run this once over SSH: open ~/sbx-daemon-restart.command"
fi

# 8. An empty folder for tests
say "Lab folder"
run mkdir -p "$LAB_DIR"
echo "   $LAB_DIR"
echo "   Keep it empty. The plugin you test can read and change anything in it."

cat <<EOF

Done. To test a plugin in a throwaway sandbox:

  sbx run --rm --skills off --name plugin-lab claude "$LAB_DIR"

Inside it:
  /login                                   sign in to Claude (every new sandbox)
  /plugin marketplace add OWNER/REPO       add the plugin's marketplace
  /plugin install PLUGIN@MARKETPLACE       install the plugin
  /exit                                    leave; the sandbox is deleted

The first run downloads the Claude image, so it takes a few minutes.
EOF
