#!/bin/sh
# Installs the benchturn CLI and sets it up.
#   curl -fsSL https://benchturn.com/install.sh | sh
# It records each Claude Code / Codex send (git tree before and after, plus the
# transcript slice) and uploads it in the background. Setup signs you in with GitHub and
# offers to upload past sessions it finds (GEN_NO_AGENT=1 skips that offer, e.g. when an
# agent runs this script). Docs: https://benchturn.com/#install
#
# benchturn is a self-contained binary: nothing else to install. It goes to
# ~/.local/share/benchturn (one folder per version, `current` points at the newest) with
# `benchturn` linked into ~/.local/bin. The CLI was called `gen` before 0.5.0; that name is
# linked too, so older instructions keep working.
set -eu

BASE="${GEN_BIN_BASE:-https://benchturn.com/cli/bin}"
ROOT="${GEN_INSTALL_ROOT:-$HOME/.local/share/benchturn}"
BIN_DIR="${GEN_BIN_DIR:-$HOME/.local/bin}"
# Your invite code. A personal install link (install.sh?r=...) fills this in.
REF="${GEN_REF:-}"

say() { printf '%s\n' "$*"; }
fail() { printf 'error: %s\n' "$*" >&2; exit 1; }

command -v git >/dev/null 2>&1 || fail "git is required. Install it, then re-run this script."
command -v tar >/dev/null 2>&1 || fail "tar is required."

case "$(uname -s)" in Darwin) os=darwin ;; Linux) os=linux ;; *) fail "benchturn runs on macOS and Linux." ;; esac
case "$(uname -m)" in x86_64|amd64) arch=x86_64 ;; arm64|aarch64) arch=arm64 ;; *) arch=$(uname -m) ;; esac
PLATFORM="$os-$arch"

LINE=$(curl -fsSL "$BASE/manifest.txt" | grep "^$PLATFORM " | head -1) || true
[ -n "$LINE" ] || fail "no benchturn build for $PLATFORM yet. Write to hello@benchturn.com and we'll add one."
# shellcheck disable=SC2086
set -- $LINE
VERSION=$2 SHA=$3 FILE=$4

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
say "Downloading benchturn $VERSION for $PLATFORM ..."
curl -fsSL "$BASE/$FILE" -o "$TMP/$FILE"
if command -v sha256sum >/dev/null 2>&1; then GOT=$(sha256sum "$TMP/$FILE" | cut -d' ' -f1)
else GOT=$(shasum -a 256 "$TMP/$FILE" | cut -d' ' -f1); fi
[ "$GOT" = "$SHA" ] || fail "download checksum mismatch for $FILE; please try again."

mkdir -p "$ROOT/versions" "$BIN_DIR"
if [ ! -x "$ROOT/versions/$VERSION/benchturn/benchturn" ]; then
  mkdir "$TMP/x"
  tar xzf "$TMP/$FILE" -C "$TMP/x"
  rm -rf "$ROOT/versions/$VERSION"
  mv "$TMP/x" "$ROOT/versions/$VERSION"
fi
ln -sfn "versions/$VERSION" "$ROOT/current"
ln -sf "$ROOT/current/benchturn/benchturn" "$BIN_DIR/benchturn"
ln -sf "$ROOT/current/benchturn/benchturn" "$BIN_DIR/gen"
BENCHTURN="$BIN_DIR/benchturn"

say ""
if [ -n "$REF" ]; then
  "$BENCHTURN" init --ref "$REF"
else
  "$BENCHTURN" init
fi

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) case "${SHELL:-}" in *zsh) RC='~/.zshrc' ;; *bash) RC='~/.bashrc' ;; *) RC='~/.profile' ;; esac
     say "Add $BIN_DIR to your PATH to run 'benchturn' directly, e.g.:"
     say "  echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> $RC" ;;
esac
