#!/bin/sh
# SwarmHub's installer: curl -fsSL https://swarmhub.wtf/install | sh
#
# What it does, in order, and nothing else:
#  1. Downloads SwarmHub's client into a temporary folder and checks it: the release key's signature on the file list
#     (ssh-keygen, which comes with macOS), then every file's SHA-256 against that list. Any mismatch stops here, with
#     nothing changed.
#  2. Puts the client in ~/.agent-board/bin. A Mac that already has another release updates instead (board.py update,
#     the same checks). Python's PyNaCl, which the sign-in needs, and certifi's
#     certificate roots go in a folder of its own, ~/.agent-board/venv.
#  3. Connects this Mac to your SwarmHub account: board.py login shows a code, you click Connect in the browser.
#  4. Asks, then gives Claude Code one SwarmHub tool, "join", for your user. No session joins by itself: a running one
#     joins when you ask it to, after you approve it in the browser.
#  5. Asks whether to also set up a crew on this Mac (Wheelhouse, the service and a captain), and if so runs that
#     setup, after checking its SHA-256 against the one pinned below.
# It asks before writing anything outside ~/.agent-board, never prints a token, and is safe to run again. On screen it
# shows one line per step (Designer 3ecc03a7a3ab); everything else goes to ~/.agent-board/install.log (0600, started
# fresh every run, never a token), which a failure points to.
set -eu

URL="https://swarmhub.wtf"
# SwarmHub's release key, the same one board.py update checks against (client/board.py RELEASE_SIGNERS).
SIGNER="swarmhub-release ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBzAoyPtQqef8I+jPSigGN8w+bPZIGcB3w7o22WKE/iI"
FILES="board.py board_mcp.py board_hook.py dispatch.py"
# The crew setup: ai-startup/agent-commander bin/crew-setup at a6969dba (PR 927), pinned. Empty: not offered.
CREW_SHA256="f2f08178e29d857fd56ed576d7cadbeccea7d0df9181dc0e1dce3f909e0ea4c4"

BOARD="$HOME/.agent-board"
BIN="$BOARD/bin"
PY="$BOARD/venv/bin/python"
# [1.48] Off macOS (Linux, Windows under WSL), the words and the fixes the person is given (Eng Lead 16cc4a0a7f73;
# Designer a885e71738e7): Ubuntu's package names, never xcode-select.
if [ "$(uname -s)" = Darwin ]; then
  MACHINE="this Mac"
  TOOLS_FIX="Install Apple's command line tools with this, then run the installer again:
    xcode-select --install"
  VENV_FIX="Fix that, then run this again."
else
  MACHINE="this machine"
  TOOLS_FIX="Install it with your system's package manager (on Ubuntu: sudo apt install python3 curl openssh-client), then run the installer again."
  VENV_FIX="On Ubuntu: sudo apt install python3-venv, then run this again."
fi
LOG="$BOARD/install.log"
logging=0

# Log writes: stdin appended to the log only while its path is still the file start_log made (same device and inode,
# a regular file). Never through a link (O_NOFOLLOW), never a new file (no O_CREAT), never waiting on a FIFO
# (O_NONBLOCK). The shell itself never opens the path (Codex ac95b75e99da, 345fcac40880, 44072ed45404).
LOGW='import os, stat, sys
try:
    fd = os.open(sys.argv[1], os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW | os.O_NONBLOCK)
except OSError:
    sys.exit(1)
st = os.fstat(fd)
if not stat.S_ISREG(st.st_mode) or "%d %d" % (st.st_dev, st.st_ino) != sys.argv[2]:
    sys.exit(1)
data = sys.stdin.buffer.read()
while data:
    data = data[os.write(fd, data):]'
logw() { [ "$logging" = 1 ] || { cat > /dev/null; return 0; }; python3 -I -c "$LOGW" "$LOG" "$made" 2>/dev/null || true; }
log() { [ "$logging" = 1 ] || return 0; printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" | logw; }
say() { printf '%s\n' "$*"; log "$*"; }
# fail "What didn't happen." ["The fix, on lines of its own."]: the gist, then the fix, then where the details are.
fail() {
  printf '✗ %s\n' "$1" >&2
  [ -n "${2:-}" ] && printf '%s\n' "$2" >&2
  log "✗ $1 ${2:-}"
  [ "$logging" = 1 ] && printf "Details: ~/.agent-board/install.log (send it to whoever invited you if this doesn't fix it)\n" >&2
  exit 1
}

# The log, fresh each run. Whatever is at its path (last run's log, or a link) is renamed to install.log.prev, the name
# itself and never what a link points to; then the new log is made in one exclusive open (O_EXCL | O_NOFOLLOW, 0600),
# and $made names that file for logw. If anything else is there by then, the run keeps no log.
start_log() {
  [ -d "$BOARD" ] || { mkdir -p "$BOARD" && chmod 700 "$BOARD"; } \
    || fail "Couldn't make ~/.agent-board." "Check that your home folder is yours and has space, then run this again."
  # One already there may be open to others (0775), and then the crew setup won't keep its log in it: close it, if it's a
  # real folder of this user's, never what a link points to (Team Builder 2bf9cf2ba7f0).
  if [ ! -L "$BOARD" ] && [ -O "$BOARD" ]; then chmod go-rwx "$BOARD" 2>/dev/null || true; fi
  made=$(python3 -I -c 'import os, sys
p = sys.argv[1]
if os.path.lexists(p): os.replace(p, p + ".prev")
st = os.fstat(os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600))
print(st.st_dev, st.st_ino)' "$LOG" 2>/dev/null) || return 0
  logging=1
  log "SwarmHub installer, $(uname -s) $(sw_vers -productVersion 2>/dev/null || uname -r), $(python3 --version 2>&1)"
}

# quietly <command…>: its output goes to the log, and stays in $tmp/out for a failure's fix lines.
quietly() {
  "$@" > "$tmp/out" 2>&1 && st=0 || st=$?
  sed 's/^/    /' "$tmp/out" | logw
  return "$st"
}

# Questions come from the terminal, not from the pipe this script arrived on. "?" prints why, then asks again.
ask() {   # ask "Question?" Y|N "Why, for ?"  → 0 for yes
  if [ "$2" = Y ]; then hint="[Y/n/?]"; else hint="[y/N/?]"; fi
  while :; do
    printf '%s %s ' "$1" "$hint" > /dev/tty
    # No answer (Ctrl+D, a closed terminal) is never a yes: stop.
    read -r reply < /dev/tty || { printf '\n' > /dev/tty; fail "Stopped at a question." "Run this again when you're ready."; }
    case "$reply" in
      \?*) printf '%s\n' "$3" > /dev/tty ;;
      [Yy]*) log "$1 yes"; return 0 ;;
      [Nn]*) log "$1 no"; return 1 ;;
      *) if [ "$2" = Y ]; then log "$1 yes (Enter)"; return 0; else log "$1 no (Enter)"; return 1; fi ;;
    esac
  done
}

sha256() {
  if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1; else sha256sum "$1" | cut -d' ' -f1; fi
}

fetch() {   # fetch <path under URL> <file>: https only, no redirects to elsewhere, 2 minutes at most; curl's error to the log
  curl -fsS --proto =https --max-time 120 --max-filesize 2000000 -o "$2" "$URL/$1" 2> "$tmp/curl.err" && return 0
  st=$?
  log "$URL/$1: $(cat "$tmp/curl.err")"
  return "$st"
}

main() {
  # Ctrl+C stops it, wherever it is: never "no answer, so the default".
  trap 'printf "\nStopped.\n" >&2; log "Stopped (Ctrl+C)."; exit 130' INT TERM
  ( : < /dev/tty ) 2>/dev/null || fail "This needs a terminal for its questions." "Run it in Terminal. Nothing was changed."
  for t in python3 curl ssh-keygen; do
    command -v "$t" >/dev/null 2>&1 || fail "$t isn't installed." "$TOOLS_FIX
Nothing was changed."
  done
  python3 -c 'import sys; sys.exit(sys.version_info < (3, 9))' 2>/dev/null \
    || fail "SwarmHub needs Python 3.9 or newer (python3 --version)." "$TOOLS_FIX
Nothing was changed."

  start_log
  say "SwarmHub setup: 3 steps, about 2 minutes. You'll click once in your browser."
  say ""

  # 1. Download and check, in a temporary folder.
  tmp=$(mktemp -d "${TMPDIR:-/tmp}/swarmhub-install.XXXXXX")
  trap 'rm -rf "$tmp"' EXIT
  log "Downloading $URL/client/manifest.json and its signature into $tmp"
  fetch client/manifest.json "$tmp/manifest.json" || fail "Couldn't download SwarmHub's client." "Check your connection, then run this again. Nothing was installed."
  fetch client/manifest.json.sig "$tmp/manifest.json.sig" || fail "Couldn't download the client's signature." "Run this again. Nothing was installed."
  printf '%s\n' "$SIGNER" > "$tmp/allowed_signers"
  quietly ssh-keygen -Y verify -f "$tmp/allowed_signers" -I swarmhub-release -n swarmhub-client -s "$tmp/manifest.json.sig" \
    < "$tmp/manifest.json" \
    || fail "The client isn't signed by SwarmHub's release key, so nothing was installed."
  log "Release key signature checked: $SIGNER"
  for f in $FILES; do
    want=$(python3 -I -c 'import json,sys
m = json.load(open(sys.argv[1]))
print(next((x["sha256"] for x in m["files"] if x.get("name") == sys.argv[2]), ""))' "$tmp/manifest.json" "$f") || want=""
    [ -n "$want" ] || fail "The signed file list doesn't name $f, so nothing was installed."
    fetch "client/$f" "$tmp/$f" || fail "Couldn't download $f." "Run this again. Nothing was installed."
    [ "$(sha256 "$tmp/$f")" = "$want" ] || fail "$f doesn't match the signed file list, so nothing was installed." "Run this again."
    log "$f: SHA-256 $want matches the signed list"
  done
  say "✓ Downloaded and checked SwarmHub's client"

  # 2. Install; leave a matching client alone; update another release through its own checks.
  # First, PyNaCl: the browser sign-in seals the token to a key made on this Mac. certifi: Mozilla's vetted roots, which
  # board.py checks SwarmHub's certificate against when this Python has none of its own (python.org's, before Install
  # Certificates.command). In a venv of SwarmHub's own, so neither Homebrew's Python (which refuses pip installs) nor
  # your other Python projects are touched.
  if ! "$PY" -c 'import nacl, certifi' 2>/dev/null; then
    # A venv without pip (Ubuntu without python3-venv leaves one) is made again, so a rerun after the fix works.
    { [ -x "$PY" ] && "$PY" -m pip --version >/dev/null 2>&1; } || quietly python3 -m venv --clear "$BOARD/venv" \
      || fail "Couldn't make ~/.agent-board/venv." "$(tail -n 4 "$tmp/out")
$VENV_FIX"
    quietly "$PY" -m pip install --disable-pip-version-check pynacl certifi \
      || fail "Couldn't install PyNaCl, which the sign-in needs." "$(tail -n 4 "$tmp/out")
Check your connection, then run this again."
    log "Installed PyNaCl and certifi (from PyPI) in ~/.agent-board/venv"
  fi
  # An older client (one a failed setup left here, say) updates through Python's own certificates, and on a Python with
  # none it can't reach SwarmHub at all: hand that one run certifi's (Codex 15f5b2b4b003). Never when Python has its own.
  ca=""
  python3 -I -c 'import ssl, sys; c = ssl.create_default_context(); sys.exit(0 if c.cert_store_stats()["x509_ca"] or c.get_ca_certs() else 1)' 2>/dev/null \
    || ca=$("$PY" -c 'import certifi; print(certifi.where())' 2>/dev/null) || ca=""
  same=1
  for f in $FILES; do
    [ -f "$BIN/$f" ] && [ "$(sha256 "$BIN/$f")" = "$(sha256 "$tmp/$f")" ] || same=0
  done
  if [ "$same" = 1 ]; then
    log "The client in ~/.agent-board/bin is already installed and current"
  elif [ -f "$BIN/board.py" ]; then
    log "Another release is in ~/.agent-board/bin: board.py update"
    if [ -n "$ca" ]; then
      log "This Python has no certificates of its own: the update uses certifi's ($ca)"
      quietly env SSL_CERT_FILE="$ca" python3 "$BIN/board.py" update
    else
      quietly python3 "$BIN/board.py" update
    fi || fail "Couldn't update SwarmHub's client." "$(tail -n 6 "$tmp/out")
Fix that, then run this again."
  else
    mkdir -p "$BIN"
    for f in $FILES; do
      cp "$tmp/$f" "$BIN/.$f.new" && chmod 755 "$BIN/.$f.new" && mv -f "$BIN/.$f.new" "$BIN/$f"
    done
    python3 -I -c 'import json,sys
m = json.load(open(sys.argv[1]))
open(sys.argv[2], "w").write(json.dumps({"serial": m["serial"], "version": m["version"]}) + "\n")' "$tmp/manifest.json" "$BIN/release.json"
    log "Installed the client in ~/.agent-board/bin"
  fi

  say "✓ Installed it"

  # 3. Connect this Mac, unless it already is: who it is, and its token where config.json says (as board.py connect
  # reads it), else the default place. A Mac set up another way keeps its token and config as they are.
  token_file=$(python3 -I -c 'import json, os, sys
try:
    f = json.load(open(sys.argv[1])).get("token_file")
except (OSError, ValueError, AttributeError):
    f = None
print(os.path.expanduser(f) if isinstance(f, str) and f else sys.argv[2])' "$BOARD/config.json" "$BOARD/secrets/agents.token")
  if [ -s "$BOARD/owner" ] && [ -s "$token_file" ]; then
    log "This machine was already connected"
  else
    # BOARD_INSTALLER=1: login prints the installer's two lines and logs the rest, and leaves out its own "Run board.py
    # login again", so only the line below says how to retry
    BOARD_INSTALLER=1 BOARD_INSTALL_LOG="${made:-}" "$PY" "$BIN/board.py" login < /dev/tty || fail "Couldn't connect $MACHINE." "Run this again to try once more."
  fi
  handle=$(cat "$BOARD/owner")
  say "✓ Connected as $handle"

  # 4. Claude Code: one tool, join, for this user. joined=1 when it has it, declined=1 after a no, so "Next" only says what
  # works (QA 153f2d3029ac; Designer dae3e3bc8bd0).
  joined=0 declined=0
  if command -v claude >/dev/null 2>&1; then
    current=$(cd "$HOME" && claude mcp get board 2>/dev/null || true)   # from home: the user's own, not a project's
    if printf '%s' "$current" | grep -q "BOARD_JOIN=1"; then
      say "✓ Claude Code has SwarmHub's join tool"
      joined=1
    elif [ -n "$current" ]; then
      say "Claude Code already has a SwarmHub server for your user, set up another way. Leaving it as it is."
    elif ask "Let Claude Code sessions join SwarmHub when you ask them to?" Y \
      "This adds one tool, join, to Claude Code for your user. A session isn't on SwarmHub until you ask it to join; then you approve it in the browser."; then
      # The name before -e: -e takes several values, so it would swallow the name (QA 17f8ffa1491f).
      quietly claude mcp add --scope user board -e BOARD_JOIN=1 -- "$PY" "$BIN/board_mcp.py" \
        || fail "Claude Code didn't add the join tool." "$(tail -n 4 "$tmp/out")
Run this again."
      say "✓ Added SwarmHub's join tool to Claude Code"
      joined=1
    else
      declined=1
    fi
  else
    say "Claude Code isn't installed, so it was skipped. After installing it, run this again."
  fi

  # 5. The crew, if offered.
  # The crew is Mac-only (Wheelhouse and the Claude app): never offered elsewhere (Eng Lead 16cc4a0a7f73).
  if [ -n "$CREW_SHA256" ] && [ "$(uname -s)" = Darwin ] && ask "Also set up a crew on this Mac: a captain agent and Wheelhouse?" N \
    "A crew is a captain agent that runs your other agents, and Wheelhouse, where you watch them. Setting it up takes about 20 minutes and stops a few times for you. The setup is checked against the copy this installer pins before it runs."; then
    fetch client/crew-setup "$tmp/crew-setup" || fail "Couldn't download the crew setup." "Run this again."
    [ "$(sha256 "$tmp/crew-setup")" = "$CREW_SHA256" ] \
      || fail "The crew setup doesn't match the one this installer pins, so it wasn't run."
    log "Crew setup: SHA-256 $CREW_SHA256 matches the pin; running it"
    # Exit 4: it stopped for something only the person can do, and its own message is the last thing on screen, so
    # nothing more is printed under it (Builders 307391e26ce4). Any other failure gets the usual lines.
    crew=0
    bash "$tmp/crew-setup" --handle "$handle" < /dev/tty || crew=$?
    if [ "$crew" = 4 ]; then log "Crew setup stopped for the person (exit 4); its message on screen says what to do"; exit 1; fi
    [ "$crew" = 0 ] || fail "The crew setup stopped (above)." "Run this again: it picks up where it stopped."
  fi

  say "✓ Done."
  say ""
  [ "$joined" = 1 ] && say "Next: in Claude Code, ask: join SwarmHub as scout"
  [ "$declined" = 1 ] && say "Next: to put Claude Code on SwarmHub later, run this again and answer y."
  [ "$logging" = 1 ] && say "Every detail is in ~/.agent-board/install.log"
  return 0
}

main "$@"
