#!/usr/bin/env bash
# gbrain-box.sh: a self-hosted GBrain on a Prized box, in one run. Guide: https://prized.dev/docs/gbrain
#
# On the box it installs Bun and GBrain (stable channel), creates a keyless PGLite brain, optionally
# indexes a folder of Markdown (GBRAIN_NOTES, best a git repo), runs the brain as an always-on HTTP MCP
# server on the box's loopback (127.0.0.1:3131, a systemd user service), and connects the box's own
# Claude Code and Codex to it. It also makes a credential for your laptop. Nothing is published: your
# laptop reaches the server through Prized's port forwarding.
#
#   curl -fsSL https://prized.dev/docs/gbrain/gbrain-box.sh | prized exec BOX -- bash -s
#   curl -fsSL https://prized.dev/docs/gbrain/gbrain-box.sh | prized exec BOX -- 'GBRAIN_NOTES=~/company bash -s'
#
# GBrain is Garry Tan's MIT-licensed project (https://github.com/garrytan/gbrain); this script is Prized's.
#
# Safe to run again: each step skips what is already there, and the box agents get fresh tokens. Tokens
# last 90 days; to renew the laptop's, delete ~/.gbrain/private/laptop.json on the box and run this again.
# Follows GBrain's own docs: README "Here's how to self-host it", docs/INSTALL.md and
# docs/guides/remote-mcp.md ("No Tailscale, no tunnel" and "PGLite brains").
set -euo pipefail

main() {
  # The whole body is one function, so bash has read all of it before anything runs; children get no stdin.
  exec </dev/null
  umask 077   # every credential file this makes is readable by you alone

  PORT=3131
  NOTES="${GBRAIN_NOTES:-}"
  URL="http://127.0.0.1:${PORT}/mcp"
  PRIV="$HOME/.gbrain/private"
  TTL=7776000   # 90 days (GBrain's default is 30; it refuses a year)
  export PATH="$HOME/.bun/bin:$HOME/.local/bin:$PATH"
  export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
  t0=$(date +%s)

  step "1/7 Bun"
  local missing=""
  for tool in unzip jq; do command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"; done
  if [ -n "$missing" ]; then
    sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $missing >/dev/null
  fi
  if command -v bun >/dev/null 2>&1; then
    echo "bun $(bun --version) already here"
  else
    curl -fsSL https://bun.sh/install | bash >/dev/null
    echo "bun $(bun --version) installed"
  fi

  step "2/7 GBrain (stable channel, from GitHub; never the npm package)"
  if command -v gbrain >/dev/null 2>&1; then
    echo "$(gbrain --version) already here"
  else
    run bun install -g github:garrytan/gbrain#stable
    gbrain --version
  fi

  step "3/7 Brain (PGLite, keyless: keyword search until you add an embedding key)"
  if [ -f "$HOME/.gbrain/config.json" ]; then
    echo "brain already configured"
  else
    run gbrain init --pglite --no-embedding --non-interactive
    echo "brain ready at ~/.gbrain/brain.pglite"
  fi
  mkdir -p "$PRIV"; chmod 700 "$PRIV"

  step "4/7 Notes folder"
  if [ -n "$NOTES" ]; then
    NOTES="$(cd "$NOTES" && pwd)"
    # PGLite has one writer: source changes happen while the server is stopped, and it starts again even on failure
    if systemctl --user is-active --quiet gbrain-serve.service; then
      systemctl --user stop gbrain-serve.service
      trap 'systemctl --user start gbrain-serve.service' EXIT
    fi
    if [ ! -f "$PRIV/notes.path" ]; then
      run gbrain sources add notes --path "$NOTES" --federated --force
      echo "$NOTES" > "$PRIV/notes.path"
    elif [ "$(cat "$PRIV/notes.path")" != "$NOTES" ]; then
      echo "note: the notes source already points at $(cat "$PRIV/notes.path"); keeping it"
    fi
    gbrain sync --source notes 2>&1 | grep -E 'imported|rror' | tail -n 3 || true
    [ -d "$NOTES/.git" ] || echo "note: $NOTES is not a git repository; to re-sync it later while the server runs, make it one (git init, commit)"
  else
    echo "none (set GBRAIN_NOTES=<folder> to index one)"
  fi
  READ="default"; [ -f "$PRIV/notes.path" ] && READ="default,notes"

  step "5/7 Always-on server on 127.0.0.1:${PORT} (systemd user service, nothing published)"
  if [ -f "$HOME/.gbrain/serve/expose.json" ]; then
    systemctl --user start gbrain-serve.service
  else
    run gbrain mcp expose --no-tailscale --yes --port "$PORT"
  fi
  trap - EXIT
  curl -fsS -m 30 --retry 15 --retry-delay 1 --retry-connrefused "http://127.0.0.1:${PORT}/health"; echo

  step "6/7 Connect this box's agents"
  local connected=0
  if command -v claude >/dev/null 2>&1; then
    grant box-claude-code claude-code
    if [ "$(jq -r '.mcpServers.gbrain.type // empty' "$HOME/.claude.json" 2>/dev/null)" = "http" ]; then
      # tokens expire (90 days); a re-run swaps in a fresh one
      run gbrain connect "$URL" --harness claude-code --credentials-file "$PRIV/box-claude-code.json" --install --fresh-token
      echo "claude-code: already connected; token renewed"
    else
      # an old stdio entry (from `gbrain setup claude-code`) cannot open the brain while the server holds it
      if [ -n "$(jq -r '.mcpServers.gbrain // empty' "$HOME/.claude.json" 2>/dev/null)" ]; then claude mcp remove gbrain -s user >/dev/null 2>&1 || true; fi
      run gbrain connect "$URL" --harness claude-code --credentials-file "$PRIV/box-claude-code.json" --install
      echo "claude-code: connected"
    fi
    run gbrain setup claude-code --instructions-only
    claude mcp list 2>/dev/null | grep -E '^gbrain' || true
    connected=1
  fi
  if command -v codex >/dev/null 2>&1; then
    grant box-codex codex
    if codex mcp list 2>/dev/null | grep -qE "^gbrain +http://127\.0\.0\.1:${PORT}/mcp"; then
      run gbrain connect "$URL" --harness codex --credentials-file "$PRIV/box-codex.json" --install --fresh-token
      echo "codex: already connected; token renewed"
    elif codex mcp list 2>/dev/null | grep -qE '^gbrain '; then
      # an older entry (gbrain's managed block in ~/.codex/config.toml); leave it to the person
      echo "codex: has another gbrain entry; run: gbrain setup codex --remove, then this script again"
    else
      run gbrain connect "$URL" --harness codex --credentials-file "$PRIV/box-codex.json" --install
      echo "codex: connected"
    fi
    run gbrain setup codex --instructions-only
    connected=1
  fi
  [ "$connected" = 1 ] || echo "no Claude Code or Codex on this box; connect one later with gbrain connect"

  step "7/7 A credential for your laptop"
  grant laptop claude-code "laptop-$(date -u +%Y%m%d%H%M)"
  jq -r .access_token "$PRIV/laptop.json" > "$PRIV/laptop.token"; chmod 600 "$PRIV/laptop.token"
  echo "saved in ~/.gbrain/private/laptop.token (0600; good until $(date -d @"$(jq -r .expires_at "$PRIV/laptop.json")" +%F))"

  local box; box="$(hostname)"
  printf '\nGBrain is running on this box at %s (%ss). New Claude Code and Codex sessions here use it.\n' "$URL" "$(( $(date +%s) - t0 ))"
  printf '\nFrom your laptop (nothing is public; the port reaches you through Prized):\n'
  printf '  prized proxy %s %s    # leave it open; not needed when %s is your default box\n' "$box" "$PORT" "$box"
  printf '  claude mcp add --transport http --scope user gbrain %s --header "Authorization: Bearer $(prized exec %s -- cat .gbrain/private/laptop.token)"\n' "$URL" "$box"
}

step() { printf '\n== %s  (+%ss)\n' "$1" "$(( $(date +%s) - t0 ))"; }

# run CMD...: quiet on success; on failure print its output and stop
run() {
  local out
  if ! out="$("$@" 2>&1)"; then
    printf 'failed: %s\n%s\n' "$*" "$out" | tail -n 25 >&2
    return 1
  fi
}

# grant FILE HARNESS [CLIENT_NAME]: a scoped MCP client, once -> $PRIV/FILE.json (0600);
# on later runs, update which sources it may read
grant() {
  local file="$PRIV/$1.json" name="${3:-$1}"
  local args=(--profile memory-writer --source default --federated-read "$READ" --url "$URL"
              --admin-token-file "$HOME/.gbrain/serve/admin-token")
  if [ ! -f "$file" ]; then
    run gbrain mcp grant "$name" --harness "$2" "${args[@]}" --token-ttl "$TTL" --credentials-out "$file" --json
    echo "$name" > "$PRIV/$1.name"
    return 0
  fi
  [ -f "$PRIV/$1.name" ] && name="$(cat "$PRIV/$1.name")"
  local cid preview rev
  cid="$(jq -r .client_id "$file")"
  preview="$(gbrain mcp grant "$name" --client "$cid" --harness "$2" "${args[@]}" --dry-run --json 2>/dev/null || true)"
  rev="$(printf '%s' "$preview" | jq -r '.before.revision // empty' 2>/dev/null || true)"
  if [ -z "$rev" ]; then echo "note: could not check $name's grant; left as it was"; return 0; fi
  # nothing to do when it already reads the same sources
  [ "$(printf '%s' "$preview" | jq -c '.before.federatedRead == .grant.federatedRead')" = "true" ] && return 0
  run gbrain mcp grant "$name" --client "$cid" --if-version "$rev" --harness "$2" "${args[@]}" --json \
    || echo "note: could not update $name's grant; left as it was"
}

main "$@"
