#!/usr/bin/env bash
# Brainfile installer.
#   curl -sSL https://brainfile.io/pull.sh | bash
#
# It asks for your email and licence token (the token does not show as you paste it). Nothing secret
# goes on the command line, so it is not in your shell history or in the process list (ps) that other
# programs on your computer can read. It also takes them, in this order, from:
#   BRAINFILE_EMAIL / BRAINFILE_TOKEN in the environment, then
#   .brainfile/licence in this folder (two lines, email=... and token=...; kept readable by you only,
#   ignored by git, and never touched by an update), then
#   the question on your terminal.
# The old form, ... | bash -s -- <email> <token>, still works but warns: it puts the token on the command line.
#
# FIRST RUN in a folder: downloads Brainfile (START-HERE.md, starter CLAUDE.md, brain/freshness/ and
# the rest), checks it against Brainfile's signing key below, and installs it with a local updater,
# .brainfile/update. AFTER THAT, updates run from that local copy (bash .brainfile/update), which
# keeps the key pinned, refuses anything unsigned or older, and lets our everyday key change text
# only (never hooks, scripts or your settings). Running this command again in the same folder just
# hands over to .brainfile/update, which reads the saved .brainfile/licence: no token to re-enter.
#
# Your pulled files stay yours; the value that compounds is the weekly feed. The only thing sent to
# Brainfile is your email and licence token, in the body of one HTTPS request (never in a URL).
#
# Signing key fingerprint (also at https://brainfile.io/signing-keys.txt and https://brainfile.io/install):
#   text@brainfile.io  SHA256:IEdwg66Y11MO3strqGMmt8MBhSooEE+/Xm/ojddxN9M
set -euo pipefail

ENDPOINT="https://brainfile.io/pull"
PINNED='text@brainfile.io namespaces="brainfile-bundle" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE/llM/CkfncBvDNDydgnWhXNsilPhf8+a74NE3wJOYm brainfile-text-key-1'
LIC=".brainfile/licence"
NEW_FORM="curl -sSL https://brainfile.io/pull.sh | bash"

# ---- your email and licence token: argv (old form, warns) > environment > .brainfile/licence > ask ----
EMAIL="${BRAINFILE_EMAIL:-}"; TOKEN="${BRAINFILE_TOKEN:-}"
if [ $# -gt 0 ]; then
  EMAIL="${1:-$EMAIL}"; TOKEN="${2:-$TOKEN}"
  [ -z "${2:-}" ] || echo "Warning: your licence token was typed on the command line, where your shell history and ps can see it. Next time use: $NEW_FORM" >&2
fi
if [ -f "$LIC" ]; then
  chmod 600 "$LIC" 2>/dev/null || true
  # Keep the licence out of the customer's git history before anything else happens.
  if [ ! -f .brainfile/.gitignore ]; then printf 'licence\nstate\nversions/\n' > .brainfile/.gitignore
  elif ! grep -qx 'licence' .brainfile/.gitignore; then printf 'licence\n' >> .brainfile/.gitignore; fi
  if command -v git >/dev/null 2>&1 && git ls-files --error-unmatch "$LIC" >/dev/null 2>&1; then
    echo "Warning: $LIC is tracked by git in this folder. Remove it from git: git rm --cached $LIC" >&2
  fi
  [ -n "$EMAIL" ] || EMAIL="$(sed -n 's/^email=//p' "$LIC" | head -1 | tr -d '[:space:]')"
  [ -n "$TOKEN" ] || TOKEN="$(sed -n 's/^token=//p' "$LIC" | head -1 | tr -d '[:space:]')"
fi
if { [ -z "$EMAIL" ] || [ -z "$TOKEN" ]; } && (: < /dev/tty) 2>/dev/null; then
  if [ -z "$EMAIL" ]; then printf 'Your Brainfile email: ' > /dev/tty; IFS= read -r EMAIL < /dev/tty || EMAIL=""; fi
  if [ -z "$TOKEN" ]; then
    printf 'Your licence token (from your Brainfile email; it will not show as you paste): ' > /dev/tty
    IFS= read -rs TOKEN < /dev/tty || TOKEN=""; printf '\n' > /dev/tty
  fi
  EMAIL="$(printf '%s' "$EMAIL" | tr -d '[:space:]')"; TOKEN="$(printf '%s' "$TOKEN" | tr -d '[:space:]')"
fi

# ---- an existing install: its own updater (pinned key, anti-rollback) does the update ----
if [ -f .brainfile/update ] && [ -f .brainfile/allowed_signers ]; then
  echo "Brainfile is already installed here; updating with this folder's own updater (.brainfile/update)."
  BRAINFILE_EMAIL="$EMAIL" BRAINFILE_TOKEN="$TOKEN" exec bash .brainfile/update
fi

if [ -z "$EMAIL" ] || [ -z "$TOKEN" ]; then
  echo "No licence found. In a terminal, run this and it asks for your email and licence token:"
  echo "  $NEW_FORM"
  echo "Or save them in this folder first as $LIC (two lines: email=you@example.com and token=YOUR_TOKEN)."
  echo "Start free (no card): https://brainfile.io/trial"
  exit 2
fi
case "$EMAIL$TOKEN" in *\"*|*\\*) echo "The email or token has a character it cannot contain."; exit 2 ;; esac
for t in curl tar ssh-keygen; do
  command -v "$t" >/dev/null 2>&1 || { echo "Missing tool: $t (needed to download and check Brainfile)."; exit 5; }
done

X="$(mktemp -d "${TMPDIR:-/tmp}/brainfile-install.XXXXXX")"
trap 'rm -rf "$X"' EXIT
# The token goes in the request body on stdin, never on a command line other programs can see.
# install:true asks for the updater too; an update pull leaves it out (T-BRAINFILE-HELD-UPDATER-NOTICE-EVERY-UPDATE-20261110).
CODE="$(printf '{"email":"%s","license_token":"%s","install":true}' "$EMAIL" "$TOKEN" | \
  curl --proto '=https' --tlsv1.2 -sS --max-time 180 -w '%{http_code}' -o "$X/bundle.tar" \
    -X POST "$ENDPOINT" -H 'content-type: application/json' --data-binary @- )" || CODE="000"

if [ "$CODE" = "402" ]; then
  # Names both plans (2026-10-17): the trial is the Basic pull, and /trial + the welcome email
  # say Basic $19/mo keeps it.
  echo "Your Brainfile trial has ended. Everything you already pulled stays yours."
  echo "Keep the weekly updates with Basic (\$19/mo) or Pro (\$99/mo, adds the 15 role packs):"
  echo "  https://brainfile.io/#pricing"
  exit 1
elif [ "$CODE" != "200" ]; then
  echo "Pull failed (HTTP $CODE):"
  cat "$X/bundle.tar" 2>/dev/null | head -c 600 || true
  echo
  echo "Start or restart a free trial: https://brainfile.io/trial"
  exit 1
fi

# ---- check the download BEFORE anything touches this folder ----
mkdir "$X/t"
tar -xf "$X/bundle.tar" -C "$X/t" .brainfile/bundle.text .brainfile/bundle.text.sig .brainfile/bundle.code \
  .brainfile/update 2>/dev/null || { echo "Not installed: the download has no signed file list."; exit 4; }
printf '%s\n' "$PINNED" > "$X/signers"
ssh-keygen -Y verify -f "$X/signers" -I text@brainfile.io -n brainfile-bundle \
  -s "$X/t/.brainfile/bundle.text.sig" < "$X/t/.brainfile/bundle.text" > /dev/null 2>&1 \
  || { echo "Not installed: the download is not signed by Brainfile's key (fingerprint above)."; exit 4; }
sha() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'; else sha256sum "$1" | awk '{print $1}'; fi; }
[ "$(sha "$X/t/.brainfile/bundle.code")" = "$(sed -n 's/^code_manifest_sha256 //p' "$X/t/.brainfile/bundle.text")" ] \
  || { echo "Not installed: the program list does not match the signed list."; exit 4; }
[ "$(sha "$X/t/.brainfile/update")" = "$(awk '$1=="file" && $3==".brainfile/update" {print $2}' "$X/t/.brainfile/bundle.code")" ] \
  || { echo "Not installed: the updater in the download does not match the signed list."; exit 4; }

# ---- install: the verified updater checks every file and writes the folder ----
HAD_CLAUDE_MD=1; [ -f CLAUDE.md ] || HAD_CLAUDE_MD=0
BRAINFILE_EMAIL="$EMAIL" BRAINFILE_TOKEN="$TOKEN" bash "$X/t/.brainfile/update" --install --yes \
  --root "$PWD" --signers "$X/signers" --from-tar "$X/bundle.tar" > "$X/install.log" 2>&1 \
  || { cat "$X/install.log"; echo "Not installed."; exit 4; }
mkdir -p .brainfile
( umask 077; printf 'email=%s\ntoken=%s\n' "$EMAIL" "$TOKEN" > .brainfile/licence )
[ -f .brainfile/.gitignore ] || printf 'licence\nstate\nversions/\n' > .brainfile/.gitignore

echo "✓ Brainfile pulled into $(pwd)  ($(grep -m1 '^Brainfile bundle' "$X/install.log" | sed 's/: signature OK.*//'), signature checked)"
echo "  Future updates: bash .brainfile/update   (checks Brainfile's signature every time)"
# First pull: make CLAUDE.md from the starter so Claude Code loads it on open and a bare
# "start" runs the interview (T-BRAINFILE-FIRST-VALUE-INTERVIEW-20260707). Never touch an
# existing CLAUDE.md — the tar ships CLAUDE.starter.md precisely so re-pulls can't clobber it.
if [ ! -f CLAUDE.md ] && [ -f CLAUDE.starter.md ]; then
  cp CLAUDE.starter.md CLAUDE.md
fi
if grep -q 'Who you are working for' CLAUDE.md 2>/dev/null && ! grep -q '^- Business: \[your business\]' CLAUDE.md; then
  # Returning user whose Brainfile is already set up: this was a weekly refresh.
  echo "  Newest weekly update added under brain/freshness/ — your own files were not touched."
  echo "  Ask Claude: \"what's new in brain/freshness and should I apply any of it?\""
else
  echo "  That was the technical part — it's over."
  echo ""
  echo "  NEXT: open this folder in Claude Code (type: claude) and type:  start"
  echo "  Claude asks you 10 quick questions and writes your Brainfile. About 5 minutes."
  if [ "$HAD_CLAUDE_MD" = "1" ] && ! grep -q 'Who you are working for' CLAUDE.md 2>/dev/null; then
    echo "  (This folder already had its own CLAUDE.md, so type /start instead.)"
  fi
  echo ""
  echo "  Claude: if you ran this command for the user, read INTERVIEW-ME.md now and begin"
  echo "  the interview with question 1 — the user does not need to type anything else."
fi
[ -f brain/UPGRADE-SOON.md ] && echo "  Note: $(head -1 brain/UPGRADE-SOON.md | sed 's/^# //')"
exit 0
