#!/usr/bin/env bash
# Jet Run board installer. Usage (copy the exact line from the site):
#   curl -fsSL https://trainday.dev/install.sh | bash
# It shows a short code and opens the site; approve it there (signed in) and the board collects its own token.
# Safe to re-run: updates the board code and keeps your settings (config.local.json, which holds the token) and local prompt.
# A token still works too:  ... | bash -s -- TOKEN
# Env: JETRUN_DIR (default ~/jetrun), JETRUN_NO_SERVICE=1 (don't install the auto-start service), JETRUN_NO_MODEL=1 (skip Ollama).
set -euo pipefail
HUB="https://trainday.dev"
TOKEN="${1:-${JETRUN_TOKEN:-}}"
DIR="${JETRUN_DIR:-$HOME/jetrun}"
MODEL="qwen2.5:3b"
say() { printf '\n\033[1;36m== %s\033[0m\n' "$*"; }
die() { printf '\n\033[1;31mx %s\033[0m\n' "$*" >&2; exit 1; }
command -v curl >/dev/null || die "curl is required."
command -v python3 >/dev/null || die "python3 is required (Linux: sudo apt-get install -y python3; Mac: xcode-select --install)."
jget() { python3 -c 'import json,sys; print(json.load(sys.stdin).get(sys.argv[1]) or "")' "$1"; }
hello() { ME=$(curl -fsS -X POST -H "Authorization: Bearer $TOKEN" -H "content-type: application/json" -d '{"host":"installer"}' "$HUB/api/hello" 2>/dev/null); }
pair() {
  HOSTN=$(hostname 2>/dev/null | tr -cd 'A-Za-z0-9._-' | cut -c1-60)
  R=$(curl -fsS -X POST -H "content-type: application/json" -d "{\"host\":\"$HOSTN\"}" "$HUB/api/pair/start") || die "Couldn't reach $HUB. Check your internet connection and try again."
  CODE=$(printf '%s' "$R" | jget code); DEV=$(printf '%s' "$R" | jget device); URL=$(printf '%s' "$R" | jget url)
  [ -n "$CODE" ] || die "The hub didn't hand out a pairing code. Try again in a minute."
  printf '\n  Approve this board on the site:\n\n      \033[1m%s\033[0m\n\n  Code: \033[1;33m%s\033[0m   (open the link on any device where you are signed in)\n\n' "$URL" "$CODE"
  if [ -z "${SSH_CONNECTION:-}" ]; then (open "$URL" || xdg-open "$URL") >/dev/null 2>&1 || true; fi
  for i in $(seq 1 210); do
    sleep 3
    P=$(curl -fsS "$HUB/api/pair/poll?device=$DEV" 2>/dev/null) || continue
    case "$(printf '%s' "$P" | jget status)" in
      approved) TOKEN=$(printf '%s' "$P" | jget token); echo "Paired."; return 0 ;;
      expired) die "That code expired. Run the command again for a new one." ;;
    esac
  done
  die "Timed out waiting for approval. Run the command again for a new code."
}

say "1/6 Connecting this board to your account"
FROM_CFG=""
if [ -z "$TOKEN" ] && [ -f "$DIR/config.local.json" ]; then
  TOKEN=$(jget hub_token < "$DIR/config.local.json" 2>/dev/null || true); [ -n "$TOKEN" ] && FROM_CFG=1
fi
if [ -n "$TOKEN" ] && ! hello; then
  [ -n "$FROM_CFG" ] || die "The hub rejected that token. Run the command without a token to pair instead:  curl -fsSL $HUB/install.sh | bash"
  echo "This board's saved token no longer works. Pairing again."; TOKEN=""
fi
if [ -z "$TOKEN" ]; then pair; hello || die "Pairing finished but the hub didn't accept the board. Run the command again."; fi
AUTH="Authorization: Bearer $TOKEN"
NAME=$(printf '%s' "$ME" | jget player)
echo "You are '$NAME'."

say "2/6 Downloading the board code into $DIR"
mkdir -p "$DIR"
FILES=$(curl -fsS -H "$AUTH" "$HUB/api/board/files" | python3 -c 'import json,sys; print(" ".join(json.load(sys.stdin)["files"]))')
for f in $FILES; do
  mkdir -p "$(dirname "$DIR/$f")"
  curl -fsS -H "$AUTH" "$HUB/api/board/files/$f" -o "$DIR/$f.part" && mv "$DIR/$f.part" "$DIR/$f"
done
chmod +x "$DIR"/*.sh 2>/dev/null || true
cd "$DIR"
echo "$(echo $FILES | wc -w | tr -d ' ') files."
# the jetrun command (status, models, add, share, tune, update)
mkdir -p "$HOME/.local/bin"
printf '#!/bin/sh\nexec python3 "%s/jetrun.py" "$@"\n' "$DIR" > "$HOME/.local/bin/jetrun"
chmod +x "$HOME/.local/bin/jetrun"
JR_PATH_HINT=""
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) JR_PATH_HINT=1 ;; esac

say "3/6 Python packages"
if ! python3 -c 'import requests' 2>/dev/null; then
  python3 -m pip install --user -q -r requirements.txt 2>/dev/null \
    || python3 -m pip install --user -q --break-system-packages -r requirements.txt \
    || die "Couldn't install Python packages. On Linux: sudo apt-get install -y python3-pip python3-requests, then re-run."
fi
echo "ok"

say "4/6 Ollama and the model ($MODEL)"
if [ "${JETRUN_NO_MODEL:-}" = "1" ]; then echo "Skipped (JETRUN_NO_MODEL=1)."
else
  if ! command -v ollama >/dev/null; then
    if [ "$(uname -s)" = "Linux" ]; then curl -fsSL https://ollama.com/install.sh | sh
    elif command -v brew >/dev/null; then brew install ollama && (brew services start ollama || true)
    else die "Install Ollama from https://ollama.com/download, open it once, then re-run this command."; fi
  fi
  for i in $(seq 1 30); do
    curl -sf http://localhost:11434/api/tags >/dev/null && break
    [ "$i" = 1 ] && (nohup ollama serve >/dev/null 2>&1 &)
    sleep 1
  done
  ollama pull "$MODEL"
fi

say "5/6 Your settings"
python3 me.py NAME="$NAME" TOKEN="$TOKEN" HUB="$HUB"
if command -v nvpmodel >/dev/null; then
  (sudo -n nvpmodel -m 0 && sudo -n jetson_clocks) 2>/dev/null || echo "Jetson tip: for full speed run  sudo nvpmodel -m 0 && sudo jetson_clocks"
fi

say "6/6 Board agent"
if [ "${JETRUN_NO_SERVICE:-}" = "1" ]; then echo "Skipped (JETRUN_NO_SERVICE=1). Start it with:  cd $DIR && python3 board.py"
else ./board-service.sh install || echo "Couldn't install the auto-start service. Start the board by hand:  cd $DIR && python3 board.py"; fi
python3 hub.py --check || true
python3 jetrun.py models 2>/dev/null || true
printf '\n\033[1;32mDone.\033[0m Open %s/prompts and press Practice. Update any time with:  jetrun update\n' "$HUB"
printf 'Your own model:  jetrun add hf.co/you/your-model:Q4_K_M  (or a .gguf file)  ·  train one on a Mac:  jetrun tune\n'
if [ -n "$JR_PATH_HINT" ]; then printf 'To use jetrun, add ~/.local/bin to your PATH:  echo %s >> ~/.bashrc   (then open a new terminal)\n' "'export PATH=\$HOME/.local/bin:\$PATH'"; fi
