#!/bin/sh
# subaud.tools setup: the line the account page gives a buyer.
#
#   curl -fsSL https://subaud.tools/setup.sh | sh -s -- <key>           connect and set up, Claude Code
#   curl -fsSL https://subaud.tools/setup.sh | sh -s -- <key> pi        connect and set up, pi
#   curl -fsSL https://subaud.tools/setup.sh | sh -s -- <key> connect   connect only
#   curl -fsSL https://subaud.tools/setup.sh | sh -s -- check           check this machine
#
# The key connects the machine to the account; the agent after it is what the
# machine is set up with. `connect` after the key runs step 1 only and stops:
# nothing else is installed and the access service hears nothing more.
# `check` needs no key: it reports the system, what is installed, what kempt
# follows and what connecting and setting up would do (kempt's own dry run of
# the starter added under the person's repo, when their kempt has one), and
# changes nothing: it calls no service and writes only in its temp directory.
# A machine already connected takes the line without its key too
# (`sh -s -- pi`).
#
# In order, each step safe to run again:
#   1. connect: redeem the one-time key for this machine's token (skipped when
#      the machine already has a token the access service accepts);
#   2. prerequisites: Homebrew on a Mac, and tmux (Homebrew, or apt on Linux),
#      and Google Chrome on a Mac (Homebrew), which cast opens its page in;
#   3. agent: Claude Code from Anthropic's installer when claude is missing,
#      for either agent (pi runs on the Claude subscription through it);
#   4. the suite: kempt, then by what kempt already follows: nothing yet,
#      kempt init with the starter's suite profile; the starter, as its base or
#      as the subaud layer an earlier run added, kempt update (which pulls it
#      first); another repo, kempt reinstalled (layer add -under needs a new
#      one) and the starter added under it as the subaud layer with its suite
#      profile, so that repo, and every layer on it, wins where both overlap.
#      On the pi line, then kempt adopt pi (in that layer when the starter is
#      one) and applies with Homebrew's node@24 on PATH until pi is installed;
#      then ~/.local/bin and Homebrew on the login PATH (~/.zprofile on a Mac,
#      ~/.profile on Linux), and cast's page server restarted to pick it up;
#   5. first project: ~/subaud-start, an empty git repo, as a cast project;
#   6. done: tell the access service which agent it set up, so the account
#      page shows "set up with" it;
#   7. open: the agent in cast on "Get me started with subaud.", in its page.
#
# Every run does every step, on a new machine or one set up before, so a paste
# always leaves the machine ready to use; each step installs only what's missing.
#
# A step that needs a password with no terminal to ask at (the line was pasted
# to an agent) stops and asks for the same line in a terminal; a connection
# already made stays made, so that second paste skips step 1.
#
# The token, and the account it connects to, live in the subaud config
# directory (an absolute $SUBAUD_HOME/config, else an absolute
# $XDG_CONFIG_HOME/subaud, else ~/.config/subaud), as every tool reads it, and
# the token never reaches the output or a command line. For tests, SUBAUD_API overrides https://api.subaud.tools and
# SUBAUD_BREW_DIRS the directories Homebrew is looked for in when it isn't on PATH, and
# SUBAUD_APP_DIRS (colon-separated) the directories Google Chrome.app is looked for in.
#
# The whole script is one function, called on the last line, so nothing it
# runs can read the rest of it from the pipe.
set -eu

main() {
  # The script came through stdin; nothing below should read it.
  [ -t 0 ] || exec </dev/null

  key="${1:-}"; agent="${2:-}"; mode=setup
  case "$#:$key:$agent" in
    1:check:) key=""; mode=check ;;
    # A connected machine's line may leave out the key: `sh -s -- pi`.
    1:pi:) key=""; agent=pi ;;
    [01]:connect:|2:check:*|2:connect:*|2:pi:*) usage ;;
    [01]:*|2:*:pi) ;;
    2:*:connect) agent=""; mode=connect ;;
    *) usage ;;
  esac
  # A key has the account page's shape, XXXX-XXXX-XXXX-XXXX (access's
  # machine.NewSetupKey; any case, as it parses it): a near-miss of check
  # (Check, --help) is refused, not taken for a key on a connected machine.
  a='[A-Za-z0-9][A-Za-z0-9][A-Za-z0-9][A-Za-z0-9]'
  # shellcheck disable=SC2254  # $a is a pattern
  case "$key" in ""|$a-$a-$a-$a) ;; *) usage ;; esac
  agent="${agent:-claude}"
  api="${SUBAUD_API:-https://api.subaud.tools}"
  account_page="https://subaud.tools/account/"
  case "${SUBAUD_HOME:-}" in
    /*) cfg="$SUBAUD_HOME/config" ;;
    *) case "${XDG_CONFIG_HOME:-}" in /*) cfg="$XDG_CONFIG_HOME/subaud" ;; *) cfg="$HOME/.config/subaud" ;; esac ;;
  esac
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  case "$os" in
    darwin|linux) ;;
    *) fail "this runs on macOS and Linux (on Windows, run it inside WSL2)" ;;
  esac
  case "$agent" in pi) agent_name=pi ;; *) agent_name="Claude Code" ;; esac
  # kempt's and Claude Code's installers put their binaries here.
  PATH="$HOME/.local/bin:$PATH"; export PATH

  tmp="$(mktemp -d)" || fail "could not create a temporary directory"
  trap 'rm -rf "$tmp"' EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM

  if [ "$mode" = check ]; then check_machine; return 0; fi
  command -v curl >/dev/null 2>&1 || fail "curl is required"

  connect
  [ "$mode" != connect ] || return 0
  prerequisites
  choose_agent
  suite
  login_path
  first_project
  done_setup
  open_session
}

say() { printf '%s\n' "$*"; }
fail() { printf 'subaud setup: %s\n' "$*" >&2; exit 1; }
usage() { fail "the line is one of: curl -fsSL https://subaud.tools/setup.sh | sh -s -- <key> to connect and set up (sh -s -- <key> pi to set up with pi), sh -s -- <key> connect to connect only, or sh -s -- check to check this machine. Get yours at https://subaud.tools/account/"; }

# json_field <name>: a string field of the JSON on stdin, without jq. Go's
# encoder writes & < > as \u0026 \u003c \u003e, so those are turned back.
json_field() {
  tr -d '\n' | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" |
    sed 's/\\u0026/\&/g; s/\\u003c/</g; s/\\u003e/>/g'
}

# post <route> [token]: POST $tmp/body to the access service; the answer goes
# to $tmp/resp and its status code to stdout. The token goes through a curl
# config file, so it never appears on a command line.
post() {
  umask 077 # post runs in its own subshell: the token, body and answer files stay private
  if [ -n "${2:-}" ]; then
    printf 'header = "Authorization: Bearer %s"\n' "$2" > "$tmp/auth"
  else
    : > "$tmp/auth"
  fi
  curl -sS -o "$tmp/resp" -w '%{http_code}' -K "$tmp/auth" -H 'Content-Type: application/json' \
    --data-binary @"$tmp/body" "$api$1" || fail "could not reach the access service at $api"
}

# keep <file> <content>: write a private file in the config directory.
keep() {
  (umask 077 && mkdir -p "$cfg") || fail "could not create $cfg"
  chmod 700 "$cfg" || fail "could not make $cfg private"
  f="$(umask 077 && mktemp "$cfg/.$1.XXXXXX")" || fail "could not write $cfg/$1"
  printf '%s\n' "$2" > "$f" || { rm -f "$f"; fail "could not write $cfg/$1"; }
  mv "$f" "$cfg/$1" || { rm -f "$f"; fail "could not write $cfg/$1"; }
}

# have_tty: a terminal to ask for a password at, on stdin or /dev/tty.
have_tty() { [ -t 0 ] || ( : </dev/tty ) 2>/dev/null; }

# need_tty: stop when a password step has no terminal to ask at.
need_tty() {
  have_tty && return 0
  say "This step needs your password. Paste the same line in a terminal on this machine." >&2
  exit 1
}

# at_tty <cmd...>: run cmd with the terminal on stdin when there is one, so it
# can ask.
at_tty() { if [ -t 0 ] || ! have_tty; then "$@"; else "$@" </dev/tty; fi; }

# ---- 1. connect -----------------------------------------------------------------
connect() {
  token=""
  if [ -f "$cfg/token" ]; then token="$(tr -d ' \t\r\n' < "$cfg/token")"; fi
  if [ -n "$token" ]; then
    printf '{"product":"kempt","path":"kempt/latest"}' > "$tmp/body"
    code="$(post /links "$token")" || exit 1
    if [ "$code" != 401 ]; then
      # A machine connected before the account was kept beside the token
      # doesn't know its account's name.
      account=""
      if [ -f "$cfg/account" ]; then account="$(head -n 1 "$cfg/account")"; fi
      if [ -n "$key" ]; then
        say "Already connected to ${account:-your account}, so this line wasn't needed."
      else
        say "Already connected to ${account:-your account}."
      fi
      return 0
    fi
    token=""
  fi
  [ -n "$key" ] || fail "this machine isn't connected. Get your line at $account_page and paste it here."
  case "$key" in *[!A-Za-z0-9-]*) fail "that key isn't one the account page gives. Get a fresh line at $account_page" ;; esac
  name="$(uname -n | cut -d. -f1 | tr -d '"\134' | cut -c1-64)"; name="${name:-machine}"
  printf '{"key":"%s","name":"%s","os":"%s"}' "$key" "$name" "$os" > "$tmp/body"
  code="$(post /setup/redeem)" || exit 1
  if [ "$code" = 500 ]; then
    sleep 2
    code="$(post /setup/redeem)" || exit 1
  fi
  case "$code" in
    200) ;;
    404) say "This line has expired or was used. Get a fresh one at $account_page" >&2; exit 1 ;;
    *) fail "could not connect (the access service answered $code); paste the line again" ;;
  esac
  token="$(json_field token < "$tmp/resp")"
  [ -n "$token" ] || fail "the access service sent no token; get a fresh line at $account_page"
  keep token "$token"
  account="$(json_field account < "$tmp/resp")"
  keep account "$account"
  if [ "$mode" = connect ]; then
    say "Connected to $account. Nothing else was installed."
  else
    say "Connected to $account."
  fi
}

# ---- 2. prerequisites -----------------------------------------------------------
brew_env() {
  if ! command -v brew >/dev/null 2>&1; then
    for d in ${SUBAUD_BREW_DIRS:-/opt/homebrew/bin /usr/local/bin}; do
      if [ -x "$d/brew" ]; then PATH="$d:$PATH"; export PATH; break; fi
    done
  fi
  command -v brew >/dev/null 2>&1 || return 1
  eval "$(brew shellenv)"
}

prerequisites() {
  if [ "$os" = darwin ]; then
    if ! brew_env; then
      need_tty
      say "Installing Homebrew (it asks for your password once)…"
      at_tty /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" \
        || fail "Homebrew's installer failed"
      brew_env || fail "Homebrew was installed but brew isn't found"
    fi
    if ! command -v tmux >/dev/null 2>&1; then
      say "Installing tmux…"
      brew install tmux || fail "could not install tmux with Homebrew"
    fi
    chrome=""
    old_ifs="$IFS"; IFS=:
    for d in ${SUBAUD_APP_DIRS:-/Applications:$HOME/Applications}; do
      [ -d "$d/Google Chrome.app" ] && chrome=1
    done
    IFS="$old_ifs"
    if [ -z "$chrome" ]; then
      say "Installing Google Chrome…"
      brew install --cask google-chrome || fail "could not install Google Chrome with Homebrew"
    fi
  else
    missing=""
    command -v tmux >/dev/null 2>&1 || missing="tmux"
    command -v git >/dev/null 2>&1 || missing="git${missing:+ $missing}"
    if [ -n "$missing" ]; then
      command -v apt-get >/dev/null 2>&1 || fail "install $missing, then paste the line again"
      say "Installing ${missing}…"
      # shellcheck disable=SC2086  # one word per package
      if [ "$(id -u)" = 0 ]; then
        apt-get update || fail "apt-get update failed"
        apt-get install -y $missing || fail "could not install $missing with apt-get"
      else
        sudo -n true 2>/dev/null || need_tty
        at_tty sudo apt-get update || fail "apt-get update failed"
        at_tty sudo apt-get install -y $missing || fail "could not install $missing with apt-get"
      fi
    fi
  fi
}

# ---- 3. agent -------------------------------------------------------------------
# Claude Code for either line: pi runs on the Claude subscription through it.
# pi itself comes with the suite (step 4), so its path is found there.
choose_agent() {
  if ! command -v claude >/dev/null 2>&1; then
    say "Installing Claude Code…"
    curl -fsSL https://claude.ai/install.sh | bash || fail "Claude Code's installer failed"
    command -v claude >/dev/null 2>&1 || fail "Claude Code was installed but claude isn't found"
  fi
  if [ "$agent" = pi ]; then
    say "Using pi (and Claude Code, which pi runs on)."
  else
    agent_path="$(command -v claude)"
    say "Using Claude Code."
  fi
}

# ---- 4. the suite ---------------------------------------------------------------
suite() {
  if ! command -v kempt >/dev/null 2>&1; then
    curl -fsSL https://kempt.tools/install.sh | sh || fail "kempt's installer failed"
    command -v kempt >/dev/null 2>&1 || fail "kempt was installed but isn't found"
  fi
  # A machine whose kempt already follows the starter updates its saved
  # selection: kempt init would start the selection over, dropping the layers
  # and packages the person added since. update pulls the starter first, so a
  # machine set up before a package existed (pi) can adopt it. A machine whose
  # kempt follows the person's own repo keeps it as the base and takes the
  # starter as a layer under it: kempt init would refuse that repo's clone,
  # and under it, that repo's own versions win where the two overlap.
  read_state
  case "$base" in
    "$starter"|"${starter%.git}")
      layer=""
      say "Checking the suite…"
      at_tty kempt update || fail "kempt update failed; paste the line again to retry" ;;
    *)
      if [ -n "$layer" ]; then
        say "Checking the suite…"
        at_tty kempt update || fail "kempt update failed; paste the line again to retry"
      elif [ -n "$base" ] || [ -n "$base_dir" ]; then
        layer=subaud
        curl -fsSL https://kempt.tools/install.sh | sh || fail "kempt's installer failed"
        say "Adding the suite under your kempt repo…"
        at_tty kempt layer add -under "$layer" "$starter" -profile suite -yes \
          || fail "kempt layer add failed; paste the line again to retry"
      else
        say "Installing the suite…"
        at_tty kempt init -yes -profile suite "$starter" \
          || fail "kempt init failed; paste the line again to retry"
      fi ;;
  esac
  if [ "$agent" = pi ]; then adopt_pi; fi
}

# read_state: what kempt follows, from its state.json: $base (the base's git
# url), $base_dir (its folder) and $layer (the name of the layer whose source is
# the starter), each empty when there is none.
read_state() {
  state="${XDG_DATA_HOME:-$HOME/.local/share}/kempt/state.json"
  starter=https://github.com/subaud-tools/starter.git
  layer=""; base=""; base_dir=""
  [ -f "$state" ] || return 0
  # repo_dir is always saved; repo_url only for a base cloned from git.
  base="$(json_field repo_url < "$state")"
  base_dir="$(json_field repo_dir < "$state")"
  # The layer whose source is the starter: its name, then its source's url
  # (kempt writes name, scope, source in that order, with no { } between).
  layer="$(tr -d '\n' < "$state" | sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)"[^{}]*"source"[[:space:]]*:[[:space:]]*{[^{}]*"url"[[:space:]]*:[[:space:]]*"https:\/\/github\.com\/subaud-tools\/starter\(\.git\)\{0,1\}".*/\1/p')"
}

# adopt_pi: add the starter's pi package to the saved selection (in the
# starter's layer, $layer, when it is one) and apply it.
# pi installs with npm on Node 24. On a Mac that is Homebrew's node@24, which
# is keg-only, so its bin goes first on PATH for the rest of the run (cast's
# session starts with it); the package puts it on later login shells' PATH
# itself. On Linux kempt installs Node 24 into ~/.local/bin and npm puts pi
# there, already first on PATH. kempt inspects every step before it applies
# any and skips one blocked then, so with no Node 24 one apply installs Node,
# the next pi, the next pi's extensions, on either OS: apply until an apply
# starts with pi already on PATH, three times at most.
adopt_pi() {
  if [ "$os" = darwin ]; then PATH="$HOMEBREW_PREFIX/opt/node@24/bin:$PATH"; export PATH; fi
  say "Adding pi…"
  if [ -n "$layer" ]; then
    kempt adopt pi -layer "$layer" || fail "kempt adopt pi failed (above)"
  else
    kempt adopt pi || fail "kempt adopt pi failed (above)"
  fi
  n=0
  while [ "$n" -lt 3 ]; do
    had_pi=0; command -v pi >/dev/null 2>&1 && had_pi=1
    at_tty kempt apply -yes || fail "kempt apply failed; paste the line again to retry"
    n=$((n + 1))
    [ "$had_pi" = 0 ] || break
  done
  agent_path="$(command -v pi)" || fail "pi didn't install; paste the line again to retry"
}

# ---- 4b. the login PATH ---------------------------------------------------------
# cast's page server starts from a login shell (launchd runs `zsh -lc`), and so
# does the buyer's next terminal. Neither kempt's installer nor Homebrew's adds
# ~/.local/bin or Homebrew to it, so without this cast can't start diazo's and
# galley's page servers on a fresh Mac. Add both once, then restart cast's
# server so it picks them up.
# The lines go into the profile as written: their $ expand when it is read.
# shellcheck disable=SC2016
login_path() {
  case "$os" in darwin) profile="$HOME/.zprofile" ;; *) profile="$HOME/.profile" ;; esac
  if ! grep -q 'subaud: tools on PATH' "$profile" 2>/dev/null; then
    {
      printf '\n# subaud: tools on PATH (added by subaud.tools/setup.sh)\n'
      if [ "$os" = darwin ]; then
        printf '%s\n' 'for b in /opt/homebrew/bin/brew /usr/local/bin/brew; do [ -x "$b" ] && { eval "$("$b" shellenv)"; break; }; done'
      fi
      printf '%s\n' 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$HOME/.local/bin:$PATH"; export PATH ;; esac'
    } >> "$profile" || fail "could not add the tools to the PATH in $profile"
  fi
  if command -v cast >/dev/null 2>&1; then
    cast serve --stop >/dev/null 2>&1
    cast serve --no-open >/dev/null 2>&1 || say "cast's page server didn't restart; it starts with the next session."
  fi
}

# ---- 5. first project -----------------------------------------------------------
first_project() {
  dir="$HOME/subaud-start"
  [ -e "$dir" ] || git init -q "$dir" || fail "could not create $dir"
  case "${XDG_CONFIG_HOME:-}" in /*) roots="$XDG_CONFIG_HOME/cast/roots" ;; *) roots="$HOME/.config/cast/roots" ;; esac
  if [ -f "$roots" ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      line="$(printf '%s' "$line" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
      case "$line" in ''|'#'*) continue ;; esac
      is_project=0
      case "$line" in project:*) is_project=1; line="$(printf '%s' "${line#project:}" | sed 's/^[[:space:]]*//')" ;; esac
      case "$line" in "~"*) line="$HOME${line#\~}" ;; "\$HOME"*) line="$HOME${line#\$HOME}" ;; esac
      line="${line%/}"
      if [ "$is_project" = 1 ] && [ "$line" = "$dir" ]; then return 0; fi
      if [ "$is_project" = 0 ] && [ "$line" = "$HOME" ]; then return 0; fi
    done < "$roots"
  fi
  mkdir -p "${roots%/*}" || fail "could not create ${roots%/*}"
  printf 'project: ~/subaud-start\n' >> "$roots" || fail "could not add ~/subaud-start to $roots"
}

# ---- 6. done --------------------------------------------------------------------
done_setup() {
  printf '{"agent":"%s"}' "$agent" > "$tmp/body"
  code="$(post /setup/done "$token")" || code=000
  [ "$code" = 200 ] || say "warning: couldn't tell the account page this machine is set up (the access service answered $code); everything here is installed." >&2
}

# ---- 7. open --------------------------------------------------------------------
# cast has no flag for an agent's first prompt, and --command replaces the
# agent's launch: so --agent names the agent and --command types its launch
# with the prompt.
open_session() {
  command -v cast >/dev/null 2>&1 || fail "the suite is installed but cast isn't on PATH; open a new terminal and run: cast"
  rc=0
  out="$(cast new subaud-start/start --agent "$agent" --no-sidebar --json --command "$agent_path" "Get me started with subaud.")" || rc=$?
  # 3: the session exists already (a rerun); it is opened as it is.
  [ "$rc" = 0 ] || [ "$rc" = 3 ] || fail "could not start the cast session (cast new exited $rc)"
  socket="$(printf '%s' "$out" | json_field socket)"; pane="$(printf '%s' "$out" | json_field pane)"
  if [ -z "$socket" ] || [ -z "$pane" ]; then fail "cast new did not name its session"; fi
  if win="$(cast window --socket "$socket" --pane "$pane")"; then
    say "$win"
    say "Set up with $agent_name. The first walk is starting in cast."
  elif [ "$os" = darwin ]; then
    fail "could not open the session's window; run: cast"
  else
    say "Set up with $agent_name. Open the first walk with: tmux -S $socket attach -t subaud-start/start"
  fi
}

# ---- check this machine ---------------------------------------------------------
# The check line: what is here and what Connect and set up would do, with
# nothing changed. It calls no service and writes only in $tmp.
check_machine() {
  if [ "$os" = darwin ] && command -v sw_vers >/dev/null 2>&1; then
    system="macOS $(sw_vers -productVersion)"
  else
    system="$(uname -s) $(uname -r)"
  fi
  say "System: $system ($(uname -m))"
  say ""
  if [ "$os" = darwin ]; then
    brew_env || true
    installed Homebrew brew
  fi
  installed tmux tmux -
  if [ "$os" = linux ]; then installed git git; fi
  if [ "$os" = darwin ]; then
    chrome=missing
    old_ifs="$IFS"; IFS=:
    for d in ${SUBAUD_APP_DIRS:-/Applications:$HOME/Applications}; do
      [ -d "$d/Google Chrome.app" ] && chrome=installed
    done
    IFS="$old_ifs"
    say "Google Chrome: $chrome"
  fi
  installed "Claude Code" claude
  installed pi pi
  installed kempt kempt

  read_state
  layers=""
  if [ -f "$state" ]; then
    layers="$(tr -d '\n' < "$state" | grep -o '"name"[[:space:]]*:[[:space:]]*"[^"]*"' |
      sed 's/.*:[[:space:]]*"//; s/"$//' | tr '\n' ',' | sed 's/,$//; s/,/, /g')" || layers=""
  fi
  own=""
  say ""
  case "$base" in
    "$starter"|"${starter%.git}") say "kempt follows: the subaud starter, as its base." ;;
    *)
      if [ -z "$base" ] && [ -z "$base_dir" ]; then
        say "kempt follows: nothing yet."
      elif [ -n "$layer" ]; then
        say "kempt follows: ${base:-$base_dir}, with the subaud starter as its layer $layer."
      else
        own=1
        say "kempt follows: ${base:-$base_dir}, with ${layers:+its layers: }${layers:-no layers}."
      fi ;;
  esac

  say ""
  say "What Connect and set up would do here:"
  if [ -n "$own" ] && command -v kempt >/dev/null 2>&1; then
    if kempt layer add -help 2>&1 </dev/null | grep -q -- '-dry-run'; then
      say "It adds the subaud starter under your kempt repo, so yours is kept where both set up the same thing. kempt's plan for that (it saves nothing):"
      # Its plan runs npm ls -g and may run brew, which write their caches:
      # those go in $tmp too, as the version probes' do.
      TMPDIR="$tmp" npm_config_cache="$tmp/npm" HOMEBREW_CACHE="$tmp/cache/Homebrew" XDG_CACHE_HOME="$tmp/cache" \
        kempt layer add -under -dry-run subaud "$starter" -profile suite </dev/null \
        || say "kempt's check stopped (above)."
    else
      kver="$(kempt --version 2>/dev/null </dev/null | head -n 1 | cut -d' ' -f2)" || kver=""
      say "Your kempt (${kver:-unknown version}) is older than the overlap check; setting up updates it first."
      setup_list
    fi
  else
    setup_list
  fi
  say ""
  say "Nothing was changed."
}

# installed <name> <command> [-]: whether it is on PATH, with the first line of
# its --version (not with -, for one that has none). A --version gets five
# seconds: a Homebrew-cask claude was seen never to answer it. Its caches go
# in $tmp: brew --version writes one in ~/Library/Caches.
installed() {
  if command -v "$2" >/dev/null 2>&1; then
    v=""
    if [ -z "${3:-}" ]; then
      HOMEBREW_CACHE="$tmp/cache/Homebrew" XDG_CACHE_HOME="$tmp/cache" \
        "$2" --version </dev/null >"$tmp/version" 2>/dev/null &
      pid=$!
      ( sleep 5; kill "$pid" 2>/dev/null ) </dev/null >/dev/null 2>&1 &
      dog=$!
      wait "$pid" 2>/dev/null || true
      kill "$dog" 2>/dev/null || true
      v="$(head -n 1 "$tmp/version")"
    fi
    say "$1: installed${v:+ ($v)}"
  else
    say "$1: missing"
  fi
}

# setup_list: what Connect and set up changes, as the account page lists it
# (site.js, subaudSetupChanges); change both together.
setup_list() {
  say "- Connects the machine to your account, once: the key in the line does it, and a machine already connected skips it."
  say "- On a Mac: Homebrew, if it isn't installed, with the Apple command line tools it needs. It asks for your password once. On Linux: tmux and git from apt, with sudo."
  say "- tmux, which cast runs your sessions in, and on a Mac Ghostty and yazi, the terminal and file browser cast opens."
  say "- Claude Code, unless it's already installed (and on the pi line, pi and its extensions). It asks you to sign in the first time it opens."
  say "- The subaud tools in ~/.local/bin, kept up to date by kempt, with each tool's skills, plugin and channel."
  say "- The way of working: shared rules for your agent in their own file beside yours (one line is added to your ~/.claude/CLAUDE.md so Claude Code reads them; the rest of that file stays as it is), and the planning, testing and review skills. It also adds the worker and reviewer subagents to ~/.claude/agents, backing up any file of the same name, and a list of files Claude Code may not read to ~/.claude/settings.json, keeping your own settings."
  say "- cast's page server, running in the background, with ~/.local/bin (and Homebrew on a Mac) added to the PATH in your shell profile, and a folder ~/subaud-start for your first session."
  say "- Last, it opens your agent with its page in Chrome."
}

main "$@"
