#!/bin/bash
# RigRoute AI Benchmark -- macOS command-line install (script channel, UNSIGNED).
# Release 0.1.10, built from commit 7e4d37cbcd93fa6d29b1e96d39c0462aab9652bd. Generated by scripts/macos_bootstrap.py: do not edit.
#
# How to use it (https://labs.rigroute.dk/benchmark):
#   1. download this file, 2. compare `shasum -a 256 rigroute-benchmark-macos.sh` with the value on the
#   Labs page, 3. run `bash rigroute-benchmark-macos.sh`.
#
# What it does: checks that this is a Mac with Apple Silicon, downloads the benchmark's command-line
# program over HTTPS with curl, REFUSES it unless its SHA-256 equals the hash pinned in this file,
# installs it in ~/Library/Application Support/RigRoute/bench/<version>/ and runs `rigroute-bench quick`:
# the same engine, planner, privacy gate and upload command as the app.
#
# What it never does: ask for administrator rights, change Gatekeeper or System Integrity Protection,
# remove quarantine attributes from anything, edit your shell profile or PATH, or upload a result
# unless you ask it to. Files downloaded by curl simply never receive a quarantine attribute; that,
# and not a signature, is why macOS lets this unsigned program run. Your protection is HTTPS plus the
# pinned SHA-256 below. See docs/macos-script-distribution.md for exactly what that does and does not
# protect against.
#
# Bash 3.2 (the macOS default) compatible on purpose.

# Translated messages are printf formats on purpose (SC2059); traps call functions indirectly (SC2329, SC2317).
# shellcheck disable=SC2059,SC2329,SC2317

if [ -z "${BASH_VERSION:-}" ]; then
  if [ -f "$0" ]; then exec /bin/bash "$0" "$@"; fi
  echo "Please run this script with bash: bash rigroute-benchmark-macos.sh" >&2
  exit 64
fi
set -u
umask 022

RR_RELEASE="0.1.10"
RR_COMMIT="7e4d37cbcd93fa6d29b1e96d39c0462aab9652bd"
RR_MIN_MACOS="14"
RR_DEFAULT_BASE="https://labs.rigroute.dk/downloads/benchmark"
# Pinned per release, generated at build time from the archive bytes: version sha256 sizeBytes file
RR_PINS='
0.1.2 b4acddc318c9a071069749b2c97c16be39c51bfefcb26bf540d0655a2331c963 9772232 RigRouteBenchmark-macos-arm64-cli.tar.gz
0.1.3 a7fb2242dd9a1e52c86d44046b3f6ee960157d73d37134e8796f8c299fad5a00 9777313 RigRouteBenchmark-macos-arm64-cli.tar.gz
0.1.5 db7fb417f147c0a91d58ad0572b60668ac0c4912a7f45e4ae64761268ded29d2 9845783 RigRouteBenchmark-macos-arm64-cli.tar.gz
0.1.6 e1448943a57f1a863b734e4dbd6bcd13792f4e4d3b7d8dfe48f4224acbe9abaf 9867105 RigRouteBenchmark-macos-arm64-cli.tar.gz
0.1.8 49d6ab31869aac5ea5f550c51c835906d7cb2e9877f9b9ca76fd1e465b732ac7 58689799 RigRouteBenchmark-macos-arm64-cli.tar.gz
0.1.10 8927c1fb844c58fbed34ff7ebb988e29a531fa8c73fab3d4bc0a0a0b62dbe457 58792615 RigRouteBenchmark-macos-arm64-cli.tar.gz
'

# Exit codes: the engine's own codes pass through; this script uses 64 and up.
EX_USAGE=64; EX_PLATFORM=65; EX_INTEGRITY=66; EX_DOWNLOAD=67; EX_INSTALL=68; EX_INTERRUPTED=130
MARKER=".rigroute-script-install"

# ---------------------------------------------------------------- options
OPT_VERSION="$RR_RELEASE"; OPT_VERSION_SET=0; OPT_DRY=0; OPT_UNINSTALL=0; OPT_UPLOAD=""; OPT_INSTALL_ONLY=0
OPT_REINSTALL=0; OPT_QUIET=0; OPT_PLAIN=0; OPT_LANG=""; OPT_HELP=0; OPT_OPEN_RESULTS=0
QUICK_ARGS=()
while [ $# -gt 0 ]; do
  case "$1" in
    --version) [ $# -ge 2 ] || { echo "--version needs a value" >&2; exit "$EX_USAGE"; }
               OPT_VERSION="$2"; OPT_VERSION_SET=1; shift 2; continue ;;
    --version=*) OPT_VERSION="${1#--version=}"; OPT_VERSION_SET=1 ;;
    --dry-run) OPT_DRY=1 ;;
    --uninstall) OPT_UNINSTALL=1 ;;
    --upload) OPT_UPLOAD=yes ;;
    --no-upload) OPT_UPLOAD=no ;;
    --open-results) OPT_OPEN_RESULTS=1 ;;
    --install-only) OPT_INSTALL_ONLY=1 ;;
    --reinstall) OPT_REINSTALL=1 ;;
    --quiet|-q) OPT_QUIET=1 ;;
    --plain) OPT_PLAIN=1 ;;
    --lang) [ $# -ge 2 ] || { echo "--lang needs da or en" >&2; exit "$EX_USAGE"; }
            OPT_LANG="$2"; shift 2; continue ;;
    --lang=*) OPT_LANG="${1#--lang=}" ;;
    --help|-h) OPT_HELP=1 ;;
    --) shift; while [ $# -gt 0 ]; do QUICK_ARGS+=("$1"); shift; done; break ;;
    *) echo "Unknown option: $1 (see --help)" >&2; exit "$EX_USAGE" ;;
  esac
  shift
done

# ---------------------------------------------------------------- language
UI_LANG=en
case "$OPT_LANG" in
  da|en) UI_LANG="$OPT_LANG" ;;
  "") case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in da*|DA*) UI_LANG=da ;; esac ;;
  *) echo "--lang must be da or en" >&2; exit "$EX_USAGE" ;;
esac

if [ "$UI_LANG" = da ]; then
  T_TAGLINE="AI Benchmark · installation via Terminal · ikke-signeret"
  T_STEP1="Tjekker din Mac"; T_STEP2="Henter benchmarken"; T_STEP3="Verificerer integritet"
  T_STEP4="Klargør runtime"; T_STEP5="Kører benchmark"
  T_NOT_MAC="Dette script er kun til macOS. Til Linux og Windows: brug downloads på labs.rigroute.dk/benchmark."
  T_INTEL="Denne Mac har en Intel-processor. RigRoute AI Benchmark til macOS kræver Apple Silicon (M1 eller nyere): kommandolinjeprogrammet er kun bygget til arm64, og benchmark-runtimen i kataloget findes kun til Apple Silicon (Metal). Intet er hentet eller installeret."
  T_ROSETTA="Terminal kører under Rosetta; benchmarken kører alligevel direkte på Apple Silicon."
  T_ROOT="Kør ikke dette script som root eller med administratorrettigheder. Det installerer kun i din egen brugermappe."
  T_OLD_MACOS="er ældre end den macOS, buildet er lavet på (%s). Det er ikke testet; vi fortsætter."
  T_MAC_OK="Mac med Apple Silicon"
  T_NO_PIN="Dette script har ingen fastlåst SHA-256 for version %s. Hent scriptet for den version fra labs.rigroute.dk/benchmark."
  T_BAD_VERSION="Ugyldigt versionsnummer: %s"
  T_DRY_TITLE="Prøvekørsel: der bliver hverken hentet eller installeret noget."
  T_DRY_ENGINE="Benchmarken henter derefter selv sin runtime og testmodel fra artefaktkataloget; hver fil verificeres med SHA-256, og planlæggeren vælger størrelserne til denne Mac."
  T_DL_FAIL="Download mislykkedes (curl-fejl %s). Intet blev installeret."
  T_MISMATCH="SHA-256 passer IKKE med værdien, der er fastlåst i dette script."
  T_MISMATCH_HELP="Filen er slettet, og intet blev installeret. Prøv ikke at omgå dette: hent scriptet igen fra labs.rigroute.dk/benchmark, og skriv til kontakt@rigroute.dk, hvis det sker igen."
  T_SIZE_MISMATCH="Filstørrelsen passer ikke med den fastlåste størrelse."
  T_SUMS_MISMATCH="Serverens SHA256SUMS stemmer ikke med hashen i dette script. Intet blev installeret."
  T_MANIFEST_MISMATCH="Serverens release-manifest stemmer ikke med hashen i dette script. Intet blev installeret."
  T_VERIFIED="SHA-256 stemmer med den fastlåste værdi"
  T_CROSSCHECK="SHA256SUMS og release-manifest stemmer også"
  T_INSTALLED="Installeret i"
  T_REUSE="Allerede installeret (verificeret ved installation)"
  T_NOT_OURS="findes, men er ikke lavet af dette script; den røres ikke."
  T_NOT_OWNED="er ikke ejet af din bruger. Intet blev installeret."
  T_LAYOUT="Arkivet har ikke det forventede indhold. Intet blev installeret."
  T_RUN_HINT="Benchmarken kører nu lokalt. Den kan tage nogle minutter, især første gang (testmodellen hentes)."
  T_RESULT="Dit resultat"
  T_OUTCOME="Udfald"; T_MODEL="Model"; T_PROMPT="Prompt"; T_GEN="Generering"; T_EVIDENCE="Evidens"
  T_UPLOADSAFE="Upload-klar"; T_MEASURED="tokens/s, målt i denne kørsel"
  T_NEXT="Næste skridt"
  T_NEXT_OPEN="Åbn mappen med dit resultat:"
  T_NEXT_AGAIN="Kør igen (bruger den installerede kopi):"
  T_UPLOAD_HINT="Deling er valgfri og sker kun, hvis du beder om det. Kræver en uploadkode fra rigroute.dk/benchmark:"
  T_UPLOAD_NOW="Starter upload (du bliver bedt om koden og om at bekræfte):"
  T_NO_SUMMARY="Benchmarken afsluttede uden et resumé (kode %s). Se meddelelserne ovenfor."
  T_CANCELLED="Afbrudt. Intet halvt installeret er efterladt."
  T_UNINSTALLED="Fjernet:"
  T_NOTHING="Intet at fjerne."
  T_KEPT="Dine resultater og den hentede model/runtime er ikke slettet:"
  T_INSTALL_ONLY="Installeret. Start benchmarken med:"
  T_STAGE_detecting_hardware="Registrerer hardware"
  T_STAGE_preparing_runtime="Klargør benchmark-runtime (llama.cpp, verificeret med SHA-256)"
  T_STAGE_listing_devices="Finder enheder"
  T_STAGE_acquiring_model="Henter testmodel (verificeret med SHA-256)"
  T_STAGE_benchmarking="Måler"
  T_STAGE_sealing="Forsegler evidens"
  T_STAGE_done="Færdig"
  T_DOWNLOADING="Henter"
  T_PLAN="Plan"
else
  T_TAGLINE="AI Benchmark · Terminal install · unsigned"
  T_STEP1="Checking your Mac"; T_STEP2="Downloading benchmark"; T_STEP3="Verifying integrity"
  T_STEP4="Preparing runtime"; T_STEP5="Running benchmark"
  T_NOT_MAC="This script is for macOS only. For Linux and Windows, use the downloads on labs.rigroute.dk/benchmark."
  T_INTEL="This Mac has an Intel processor. RigRoute AI Benchmark for macOS needs Apple Silicon (M1 or later): the command-line program is built for arm64 only, and the catalogue's benchmark runtime exists only for Apple Silicon (Metal). Nothing was downloaded or installed."
  T_ROSETTA="Terminal is running under Rosetta; the benchmark still runs natively on Apple Silicon."
  T_ROOT="Do not run this script as root or with administrator rights. It installs only into your own user folder."
  T_OLD_MACOS="is older than the macOS the build was made on (%s). That is untested; continuing."
  T_MAC_OK="Mac with Apple Silicon"
  T_NO_PIN="This script has no pinned SHA-256 for version %s. Download the script for that version from labs.rigroute.dk/benchmark."
  T_BAD_VERSION="Not a valid version number: %s"
  T_DRY_TITLE="Dry run: nothing will be downloaded or installed."
  T_DRY_ENGINE="The benchmark then downloads its own runtime and test model from the artifact catalogue; every file is verified by SHA-256, and the planner chooses the sizes for this Mac."
  T_DL_FAIL="Download failed (curl error %s). Nothing was installed."
  T_MISMATCH="SHA-256 does NOT match the value pinned in this script."
  T_MISMATCH_HELP="The file was deleted and nothing was installed. Do not try to work around this: download the script again from labs.rigroute.dk/benchmark, and write to kontakt@rigroute.dk if it happens again."
  T_SIZE_MISMATCH="The file size does not match the pinned size."
  T_SUMS_MISMATCH="The server's SHA256SUMS disagrees with the hash in this script. Nothing was installed."
  T_MANIFEST_MISMATCH="The server's release manifest disagrees with the hash in this script. Nothing was installed."
  T_VERIFIED="SHA-256 matches the pinned value"
  T_CROSSCHECK="SHA256SUMS and the release manifest agree too"
  T_INSTALLED="Installed in"
  T_REUSE="Already installed (verified when it was installed)"
  T_NOT_OURS="exists but was not created by this script; it is left alone."
  T_NOT_OWNED="is not owned by your user. Nothing was installed."
  T_LAYOUT="The archive does not have the expected contents. Nothing was installed."
  T_RUN_HINT="The benchmark now runs locally. It can take a few minutes, especially the first time (the test model is downloaded)."
  T_RESULT="Your result"
  T_OUTCOME="Outcome"; T_MODEL="Model"; T_PROMPT="Prompt"; T_GEN="Generation"; T_EVIDENCE="Evidence"
  T_UPLOADSAFE="Upload-safe"; T_MEASURED="tokens/s, measured in this run"
  T_NEXT="Next steps"
  T_NEXT_OPEN="Open the folder with your result:"
  T_NEXT_AGAIN="Run it again (uses the installed copy):"
  T_UPLOAD_HINT="Sharing is optional and happens only if you ask. It needs an upload code from rigroute.dk/benchmark:"
  T_UPLOAD_NOW="Starting the upload (you will be asked for the code and to confirm):"
  T_NO_SUMMARY="The benchmark ended without a summary (exit code %s). See the messages above."
  T_CANCELLED="Cancelled. Nothing half-installed was left behind."
  T_UNINSTALLED="Removed:"
  T_NOTHING="Nothing to remove."
  T_KEPT="Your results and the downloaded model/runtime were not deleted:"
  T_INSTALL_ONLY="Installed. Start the benchmark with:"
  T_STAGE_detecting_hardware="Detecting hardware"
  T_STAGE_preparing_runtime="Preparing the benchmark runtime (llama.cpp, verified by SHA-256)"
  T_STAGE_listing_devices="Listing devices"
  T_STAGE_acquiring_model="Getting the test model (verified by SHA-256)"
  T_STAGE_benchmarking="Benchmarking"
  T_STAGE_sealing="Sealing the evidence"
  T_STAGE_done="Done"
  T_DOWNLOADING="Downloading"
  T_PLAN="Plan"
fi

# ---------------------------------------------------------------- terminal UI
# Fancy (colour, bars, spinner) only on a real terminal; NO_COLOR, TERM=dumb, --plain or a pipe give
# plain ASCII text with no escape codes at all.
FANCY=0
if [ "$OPT_PLAIN" = 0 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
  if [ -t 1 ] || [ "${RIGROUTE_BOOTSTRAP_FORCE_TTY:-}" = 1 ]; then FANCY=1; fi
fi
UTF8=0
case "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" in *UTF-8*|*utf-8*|*UTF8*|*utf8*) UTF8=1 ;; esac

ESC=$(printf '\033')
RESET=""; BOLD=""; C_BRAND=""; C_OK=""; C_WARN=""; C_FAIL=""; C_MUTED=""
if [ "$FANCY" = 1 ]; then
  RESET="${ESC}[0m"; BOLD="${ESC}[1m"
  # RigRoute palette (site/app/globals.css): primary #1769e0, success #18864b, warning #a56500,
  # failure #c63d36, muted #62666d.
  case "${COLORTERM:-}" in
    truecolor|24bit)
      C_BRAND="${ESC}[38;2;23;105;224m"; C_OK="${ESC}[38;2;24;134;75m"; C_WARN="${ESC}[38;2;165;101;0m"
      C_FAIL="${ESC}[38;2;198;61;54m"; C_MUTED="${ESC}[38;2;98;102;109m" ;;
    *) case "${TERM:-}" in
         *256color*) C_BRAND="${ESC}[38;5;26m"; C_OK="${ESC}[38;5;29m"; C_WARN="${ESC}[38;5;130m"
                     C_FAIL="${ESC}[38;5;167m"; C_MUTED="${ESC}[38;5;242m" ;;
         *) C_BRAND="${ESC}[34m"; C_OK="${ESC}[32m"; C_WARN="${ESC}[33m"; C_FAIL="${ESC}[31m"; C_MUTED="${ESC}[90m" ;;
       esac ;;
  esac
fi
if [ "$FANCY" = 1 ] && [ "$UTF8" = 1 ]; then
  SYM_OK="✓"; SYM_FAIL="✗"; SYM_WARN="!"; SYM_DOT="·"; BAR_FULL="█"; BAR_EMPTY="░"; CARD="┃"
  SPIN_FRAMES="⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏"
else
  SYM_OK="[ok]"; SYM_FAIL="[x]"; SYM_WARN="[!]"; SYM_DOT="-"; BAR_FULL="#"; BAR_EMPTY="."; CARD="|"
  SPIN_FRAMES="| / - \\"
fi
CURSOR_HIDDEN=0; LINE_OPEN=0

hide_cursor() { if [ "$FANCY" = 1 ]; then printf '%s' "${ESC}[?25l"; CURSOR_HIDDEN=1; fi; }
show_cursor() { if [ "$FANCY" = 1 ]; then printf '%s' "${ESC}[?25h"; CURSOR_HIDDEN=0; fi; }
clear_line() { if [ "$FANCY" = 1 ] && [ "$LINE_OPEN" = 1 ]; then printf '\r%s' "${ESC}[K"; LINE_OPEN=0; fi; }
say() { [ "$OPT_QUIET" = 1 ] && return 0; clear_line; printf '%s\n' "$*"; }
step() { [ "$OPT_QUIET" = 1 ] && return 0; clear_line; printf '\n%s[%s/5]%s %s%s%s\n' "$C_BRAND" "$1" "$RESET" "$BOLD" "$2" "$RESET"; }
ok() { [ "$OPT_QUIET" = 1 ] && return 0; clear_line; printf '  %s%s%s %s\n' "$C_OK" "$SYM_OK" "$RESET" "$*"; }
warn() { clear_line; printf '  %s%s%s %s\n' "$C_WARN" "$SYM_WARN" "$RESET" "$*" >&2; }
fail() { clear_line; printf '  %s%s%s %s\n' "$C_FAIL" "$SYM_FAIL" "$RESET" "$*" >&2; }
muted() { [ "$OPT_QUIET" = 1 ] && return 0; clear_line; printf '  %s%s%s\n' "$C_MUTED" "$*" "$RESET"; }
die() { code=$1; shift; fail "$*"; exit "$code"; }
tilde() { case "$1" in "$HOME"/*) printf '~%s' "${1#"$HOME"}" ;; *) printf '%s' "$1" ;; esac; }
# A path as something to paste into a shell: ~/"Library/Application Support/..." (the ~ stays outside quotes).
# shellcheck disable=SC2088  # the ~ is meant to stay literal: this text is for the user to paste
shell_path() { case "$1" in "$HOME"/*) printf '~/"%s"' "${1#"$HOME"/}" ;; *) printf '"%s"' "$1" ;; esac; }
mb() { awk -v b="$1" 'BEGIN { printf "%.1f MB", b / 1000000 }'; }

repeat() { n=$2; out=""; while [ "$n" -gt 0 ]; do out="$out$1"; n=$((n - 1)); done; printf '%s' "$out"; }
draw_bar() {  # label done total -- a real byte count, never an estimate
  if [ "$FANCY" = 0 ] || [ "$OPT_QUIET" = 1 ]; then return 0; fi
  label=$1; done_b=$2; total=$3; width=24
  [ "$total" -gt 0 ] || total=1
  [ "$done_b" -le "$total" ] || done_b=$total
  filled=$((done_b * width / total)); pct=$((done_b * 100 / total))
  printf '\r%s  %s %s%s%s%s%s %3d%%  %s / %s' "${ESC}[K" "$label" "$C_BRAND" "$(repeat "$BAR_FULL" "$filled")" \
    "$C_MUTED" "$(repeat "$BAR_EMPTY" $((width - filled)))" "$RESET" "$pct" "$(mb "$done_b")" "$(mb "$total")"
  LINE_OPEN=1
}
SPIN_I=0
# shellcheck disable=SC2086,SC2048  # split the frame list into positional parameters on purpose
spin_frame() { i=$1; set -- $SPIN_FRAMES; idx=$((i % $# + 1)); eval "printf '%s' \"\${$idx}\""; }
draw_spin() {  # label [elapsed seconds]
  if [ "$FANCY" = 0 ] || [ "$OPT_QUIET" = 1 ]; then return 0; fi
  extra=""; [ -n "${2:-}" ] && extra="  ${C_MUTED}${2}s${RESET}"
  frame=$(spin_frame "$SPIN_I"); SPIN_I=$((SPIN_I + 1))  # counted here: $(...) runs in a subshell
  printf '\r%s  %s%s%s %s%s' "${ESC}[K" "$C_BRAND" "$frame" "$RESET" "$1" "$extra"
  LINE_OPEN=1
}
spin_while() {  # pid label: wait for a background job, spinning; returns its exit status
  pid=$1; label=$2
  if [ "$FANCY" = 1 ] && [ "$OPT_QUIET" = 0 ]; then
    while kill -0 "$pid" 2>/dev/null; do draw_spin "$label"; sleep 0.1; done
    clear_line
  fi
  wait "$pid"
}

# ---------------------------------------------------------------- cleanup and Ctrl-C
TMP=""; CHILD=""; STAGING=""
cleanup() {
  if [ -n "$CHILD" ]; then kill "$CHILD" 2>/dev/null; wait "$CHILD" 2>/dev/null; CHILD=""; fi
  if [ -n "$STAGING" ] && [ -d "$STAGING" ]; then rm -rf -- "$STAGING"; fi
  if [ -n "$TMP" ] && [ -d "$TMP" ]; then rm -rf -- "$TMP"; fi
  if [ "$FANCY" = 1 ]; then
    if [ "$LINE_OPEN" = 1 ]; then printf '\r%s' "${ESC}[K"; LINE_OPEN=0; fi
    if [ "$CURSOR_HIDDEN" = 1 ]; then printf '%s' "${ESC}[?25h"; CURSOR_HIDDEN=0; fi
    printf '%s' "$RESET"
  fi
}
on_interrupt() {
  trap - INT TERM
  cleanup
  printf '\n%s\n' "$T_CANCELLED" >&2
  exit "$EX_INTERRUPTED"
}
trap on_interrupt INT TERM
trap cleanup EXIT

# ---------------------------------------------------------------- help
if [ "$OPT_HELP" = 1 ]; then
  cat <<EOF
RigRoute AI Benchmark $RR_RELEASE -- macOS (Apple Silicon) command-line install. Unsigned.

Usage: bash rigroute-benchmark-macos.sh [options] [-- options for 'rigroute-bench quick']

  --dry-run        show what would be downloaded (URLs, pinned SHA-256, size, install folder); download nothing
  --version X      install/run version X (only versions pinned in this script)
  --install-only   install, do not run the benchmark
  --reinstall      download and verify again even if this version is installed
  --uninstall      remove what this script installed (all versions, or the one given with --version)
  --upload         after the run, start 'rigroute-bench upload' (asks for an upload code and confirmation)
  --no-upload      do not upload and do not show the upload hint (nothing is uploaded unless you ask)
  --open-results   open a sanitized, private browser view after the run (no evidence upload)
  --quiet, -q      only errors and the result
  --plain          no colours, bars or spinners (also: NO_COLOR=1, TERM=dumb, or output to a pipe)
  --lang da|en     language (default: from LANG)

Installs to:  ~/Library/Application Support/RigRoute/bench/<version>/
Results go to ~/Library/Application Support/RigRoute/benchmark-runs/ (kept on --uninstall)
Pinned versions in this script:
$(printf '%s\n' "$RR_PINS" | awk 'NF == 4 { printf "  %s  sha256 %s  (%s bytes)\n", $1, $2, $3 }')
EOF
  exit 0
fi

# ---------------------------------------------------------------- banner
banner() {
  [ "$OPT_QUIET" = 1 ] && return 0
  printf '%s' "$C_BRAND"
  cat <<'EOF'
   ____   _         ____                 _
  |  _ \ (_)  __ _ |  _ \   ___   _   _ | |_   ___
  | |_) || | / _` || |_) | / _ \ | | | || __| / _ \
  |  _ < | || (_| ||  _ < | (_) || |_| || |_ |  __/
  |_| \_\|_| \__, ||_| \_\ \___/  \__,_| \__| \___|
             |___/
EOF
  printf '%s' "$RESET"
  printf '  %s%s %s %s%s\n' "$BOLD" "$(printf '%s' "$T_TAGLINE" | sed "s/ · / $SYM_DOT /g")" "$SYM_DOT" "$RR_RELEASE" "$RESET"
}

# ---------------------------------------------------------------- helpers
VERSION_RE='^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z.]+)?$'
valid_version() { [[ $1 =~ $VERSION_RE ]] && case "$1" in *..*) false ;; *) true ;; esac; }
pin_lookup() {  # version -> PIN_SHA PIN_SIZE PIN_FILE
  PIN_SHA=""; PIN_SIZE=""; PIN_FILE=""
  while read -r v sha size file; do
    [ -n "${v:-}" ] || continue
    if [ "$v" = "$1" ]; then PIN_SHA=$sha; PIN_SIZE=$size; PIN_FILE=$file; return 0; fi
  done <<EOF
$RR_PINS
EOF
  return 1
}
sha256_of() {
  if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{ print $1 }'
  else openssl dgst -sha256 -r "$1" | awk '{ print $1 }'; fi
}
size_of() { if [ -f "$1" ]; then stat -f %z "$1" 2>/dev/null || echo 0; else echo 0; fi; }

resolve_base() {  # sets BASE_ROOT and PROTO (not in a subshell, so a refusal exits the script)
  # Integrity never depends on the address: every byte is checked against the pinned hash. The
  # override exists for mirrors and tests; it must be HTTPS (plain HTTP only to this machine, for tests).
  b="${RIGROUTE_BOOTSTRAP_BASE_URL:-$RR_DEFAULT_BASE}"
  case "$b" in
    https://*) PROTO="=https" ;;
    http://127.0.0.1:*|http://localhost:*)
      [ "${RIGROUTE_BOOTSTRAP_ALLOW_HTTP_LOCALHOST:-}" = 1 ] || die "$EX_USAGE" "Refusing a non-HTTPS address: $b"
      PROTO="=http,https" ;;
    *) die "$EX_USAGE" "Refusing a non-HTTPS address: $b" ;;
  esac
  BASE_ROOT="${b%/}"
}

fetch() {  # url out max_bytes expected_bytes label
  url=$1; out=$2; max=$3; expect=$4; label=$5
  if [ "$FANCY" = 1 ] && [ "$OPT_QUIET" = 0 ] && [ "$expect" -gt 0 ]; then
    curl --fail --silent --show-error --location --proto "$PROTO" --proto-redir "$PROTO" --retry 2 \
      --connect-timeout 20 --max-filesize "$max" -o "$out" "$url" 2>"$TMP/curl.err" &
    CHILD=$!
    hide_cursor
    while kill -0 "$CHILD" 2>/dev/null; do
      draw_bar "$label" "$(size_of "$out" 2>/dev/null || echo 0)" "$expect"; sleep 0.1
    done
    wait "$CHILD"; rc=$?; CHILD=""
    [ "$rc" = 0 ] && draw_bar "$label" "$(size_of "$out")" "$expect"
    clear_line; show_cursor
  else
    curl --fail --silent --show-error --location --proto "$PROTO" --proto-redir "$PROTO" --retry 2 \
      --connect-timeout 20 --max-filesize "$max" -o "$out" "$url" 2>"$TMP/curl.err"
    rc=$?
  fi
  if [ "$rc" != 0 ]; then
    sed 's/^/    /' "$TMP/curl.err" >&2
    rm -f -- "$out"
    fail "$(printf "$T_DL_FAIL" "$rc")"
    exit "$EX_DOWNLOAD"
  fi
}

manifest_sha_for() {  # manifest file -> sha256 of the artifact with that file name ('' if none)
  i=0
  while [ "$i" -lt 64 ]; do
    f=$(plutil -extract "artifacts.$i.file" raw -o - "$1" 2>/dev/null) || return 0
    if [ "$f" = "$2" ]; then plutil -extract "artifacts.$i.sha256" raw -o - "$1" 2>/dev/null; return 0; fi
    i=$((i + 1))
  done
}

remove_ours() {  # an install dir: only ever below INSTALL_ROOT, never a link, only with our marker
  d=$1
  case "$d" in "$INSTALL_ROOT"/*) ;; *) return 1 ;; esac
  [ -L "$d" ] && { warn "$(tilde "$d") $T_NOT_OURS"; return 1; }
  [ -d "$d" ] || return 0
  [ -f "$d/$MARKER" ] || { warn "$(tilde "$d") $T_NOT_OURS"; return 1; }
  rm -rf -- "$d"
}

# ---------------------------------------------------------------- 1. checks
INSTALL_ROOT="$HOME/Library/Application Support/RigRoute/bench"
valid_version "$OPT_VERSION" || die "$EX_USAGE" "$(printf "$T_BAD_VERSION" "$OPT_VERSION")"
INSTALL_DIR="$INSTALL_ROOT/$OPT_VERSION"
BIN="$INSTALL_DIR/rigroute-bench"

banner
step 1 "$T_STEP1"
[ "$(id -u)" != 0 ] || die "$EX_PLATFORM" "$T_ROOT"
[ "$(uname -s)" = Darwin ] || die "$EX_PLATFORM" "$T_NOT_MAC"
if [ "$(sysctl -n hw.optional.arm64 2>/dev/null)" != 1 ]; then die "$EX_PLATFORM" "$T_INTEL"; fi
MACOS=$(sw_vers -productVersion 2>/dev/null || echo unknown)
ok "$T_MAC_OK $SYM_DOT macOS $MACOS"
if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null)" = 1 ]; then muted "$T_ROSETTA"; fi
case "$MACOS" in
  [0-9]*) if [ "${MACOS%%.*}" -lt "${RR_MIN_MACOS%%.*}" ] 2>/dev/null; then
            warn "macOS $MACOS $(printf "$T_OLD_MACOS" "$RR_MIN_MACOS")"; fi ;;
esac

# ---------------------------------------------------------------- uninstall
if [ "$OPT_UNINSTALL" = 1 ]; then
  removed=0
  if [ "$OPT_VERSION_SET" = 1 ]; then
    if [ -e "$INSTALL_DIR" ] || [ -L "$INSTALL_DIR" ]; then
      if remove_ours "$INSTALL_DIR"; then ok "$T_UNINSTALLED $(tilde "$INSTALL_DIR")"; removed=1; fi
    fi
  elif [ -d "$INSTALL_ROOT" ] && [ ! -L "$INSTALL_ROOT" ]; then
    for d in "$INSTALL_ROOT"/*; do
      [ -e "$d" ] || [ -L "$d" ] || continue
      if remove_ours "$d"; then ok "$T_UNINSTALLED $(tilde "$d")"; removed=1; fi
    done
  fi
  rmdir "$INSTALL_ROOT" 2>/dev/null  # only if now empty
  [ "$removed" = 1 ] || say "  $T_NOTHING"
  say "  $T_KEPT"
  say "    ~/Library/Application Support/RigRoute/benchmark-runs"
  say "    ~/Library/Caches/RigRoute/benchmark-cache"
  exit 0
fi

pin_lookup "$OPT_VERSION" || die "$EX_USAGE" "$(printf "$T_NO_PIN" "$OPT_VERSION")"
resolve_base
BASE="$BASE_ROOT/v$OPT_VERSION"
ARCHIVE_URL="$BASE/$PIN_FILE"
STEM="rigroute-benchmark-$OPT_VERSION-macos-arm64-cli"

if [ "$OPT_DRY" = 1 ]; then
  say ""
  say "  $T_DRY_TITLE"
  say "    Version            $OPT_VERSION (this script: $RR_RELEASE, commit $RR_COMMIT)"
  say "    Release manifest   $BASE/release-manifest.json"
  say "    Checksums          $BASE/SHA256SUMS"
  say "    Benchmark CLI      $ARCHIVE_URL"
  say "    SHA-256 (pinned)   $PIN_SHA"
  say "    Size (pinned)      $(mb "$PIN_SIZE") ($PIN_SIZE bytes)"
  say "    Install folder     $(tilde "$INSTALL_DIR")"
  if [ "$OPT_INSTALL_ONLY" = 1 ]; then
    say "    Then               (install only)"
  else
    say "    Then runs          rigroute-bench quick --json --progress${QUICK_ARGS[*]+ ${QUICK_ARGS[*]}}"
  fi
  say "  $T_DRY_ENGINE"
  exit 0
fi

TMP=$(mktemp -d "${TMPDIR:-/tmp}/rigroute-bench.XXXXXX") || die "$EX_INSTALL" "mktemp failed"

# ---------------------------------------------------------------- 2-3. download and verify
installed_ok() {
  [ -f "$INSTALL_DIR/$MARKER" ] && [ -x "$BIN" ] && grep -qx "sha256=$PIN_SHA" "$INSTALL_DIR/$MARKER"
}
if [ "$OPT_REINSTALL" = 0 ] && installed_ok; then
  step 2 "$T_STEP2"; ok "$T_REUSE $SYM_DOT $(tilde "$INSTALL_DIR")"
  step 3 "$T_STEP3"; ok "sha256 $PIN_SHA ($MARKER)"
  step 4 "$T_STEP4"
else
  step 2 "$T_STEP2"
  mkdir -p "$TMP/dl"
  fetch "$BASE/release-manifest.json" "$TMP/dl/release-manifest.json" 1048576 0 "release-manifest.json"
  fetch "$BASE/SHA256SUMS" "$TMP/dl/SHA256SUMS" 65536 0 "SHA256SUMS"
  fetch "$ARCHIVE_URL" "$TMP/dl/$PIN_FILE" "$PIN_SIZE" "$PIN_SIZE" "$PIN_FILE"
  ok "$PIN_FILE $SYM_DOT $(mb "$(size_of "$TMP/dl/$PIN_FILE")")"

  step 3 "$T_STEP3"
  sha256_of "$TMP/dl/$PIN_FILE" >"$TMP/sha" &
  CHILD=$!; hide_cursor; spin_while "$CHILD" "SHA-256"; CHILD=""; show_cursor
  GOT=$(cat "$TMP/sha")
  if [ "$GOT" != "$PIN_SHA" ]; then
    rm -f -- "$TMP/dl/$PIN_FILE"
    fail "$T_MISMATCH"
    say "    expected (pinned)  $PIN_SHA"
    say "    downloaded         $GOT"
    fail "$T_MISMATCH_HELP"
    exit "$EX_INTEGRITY"
  fi
  if [ "$(size_of "$TMP/dl/$PIN_FILE")" != "$PIN_SIZE" ]; then fail "$T_SIZE_MISMATCH"; exit "$EX_INTEGRITY"; fi
  ok "$T_VERIFIED"
  muted "sha256 $GOT"
  # Cross-checks against the server's own records. They can only refuse, never override the pin.
  grep -qxF "$PIN_SHA  $PIN_FILE" "$TMP/dl/SHA256SUMS" || die "$EX_INTEGRITY" "$T_SUMS_MISMATCH"
  [ "$(plutil -extract app.version raw -o - "$TMP/dl/release-manifest.json" 2>/dev/null)" = "$OPT_VERSION" ] \
    || die "$EX_INTEGRITY" "$T_MANIFEST_MISMATCH"
  [ "$(manifest_sha_for "$TMP/dl/release-manifest.json" "$PIN_FILE")" = "$PIN_SHA" ] \
    || die "$EX_INTEGRITY" "$T_MANIFEST_MISMATCH"
  ok "$T_CROSSCHECK"

  # ------------------------------------------------------------ 4a. install (user-owned, versioned)
  step 4 "$T_STEP4"
  mkdir -p "$TMP/x" || die "$EX_INSTALL" "mktemp failed"
  tar -xzf "$TMP/dl/$PIN_FILE" -C "$TMP/x" || die "$EX_INSTALL" "$T_LAYOUT"
  [ -x "$TMP/x/$STEM/rigroute-bench" ] || die "$EX_INSTALL" "$T_LAYOUT"
  mkdir -p "$INSTALL_ROOT" || die "$EX_INSTALL" "mkdir failed: $(tilde "$INSTALL_ROOT")"
  if [ ! -O "$INSTALL_ROOT" ] || [ -L "$INSTALL_ROOT" ]; then die "$EX_INSTALL" "$(tilde "$INSTALL_ROOT") $T_NOT_OWNED"; fi
  STAGING="$INSTALL_ROOT/.staging-$OPT_VERSION-$$"
  mv "$TMP/x/$STEM" "$STAGING" || die "$EX_INSTALL" "move failed"
  {
    echo "schema=rigroute.script-install/1"
    echo "version=$OPT_VERSION"
    echo "file=$PIN_FILE"
    echo "sha256=$PIN_SHA"
    echo "source=$ARCHIVE_URL"
    echo "channel=SCRIPT_UNSIGNED"
    echo "installedAt=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  } >"$STAGING/$MARKER"
  if [ -e "$INSTALL_DIR" ] || [ -L "$INSTALL_DIR" ]; then
    remove_ours "$INSTALL_DIR" || die "$EX_INSTALL" "$(tilde "$INSTALL_DIR") $T_NOT_OURS"
  fi
  mv "$STAGING" "$INSTALL_DIR" || die "$EX_INSTALL" "move failed"
  STAGING=""
  ok "$T_INSTALLED $(tilde "$INSTALL_DIR")"
fi

if [ "$OPT_INSTALL_ONLY" = 1 ]; then
  say ""
  say "  $T_INSTALL_ONLY"
  say "    $(shell_path "$BIN") quick"
  exit 0
fi

# ---------------------------------------------------------------- 4b-5. run the engine
# The engine is unchanged: `quick --json --progress` prints its summary on stdout and JSON progress
# lines on stderr (the channel the desktop app reads). Other stderr lines are shown as they are.
json_str() { printf '%s' "$2" | sed -n "s/.*\"$1\": \"\\([^\"]*\\)\".*/\\1/p"; }
json_num() { printf '%s' "$2" | sed -n "s/.*\"$1\": \\([0-9][0-9]*\\).*/\\1/p"; }
stage_label() {
  case "$1" in
    detecting-hardware) printf '%s' "$T_STAGE_detecting_hardware" ;;
    preparing-runtime) printf '%s' "$T_STAGE_preparing_runtime" ;;
    listing-devices) printf '%s' "$T_STAGE_listing_devices" ;;
    acquiring-model) printf '%s' "$T_STAGE_acquiring_model" ;;
    benchmarking) printf '%s' "$T_STAGE_benchmarking" ;;
    sealing) printf '%s' "$T_STAGE_sealing" ;;
    done) printf '%s' "$T_STAGE_done" ;;
    *) printf '%s' "$1" ;;
  esac
}
CUR=""; CUR_LABEL=""; STAGE_START=0; STEP5=0
# On a terminal a finished stage's spinner line becomes a check mark; plain output already printed its start line.
finish_stage() { if [ "$FANCY" = 1 ] && [ -n "$CUR" ] && [ "$CUR" != downloading ]; then ok "$CUR_LABEL"; fi; CUR=""; }
render() {
  blocking=0
  while :; do
    if [ "$FANCY" = 1 ] && [ "$OPT_QUIET" = 0 ] && [ "$blocking" = 0 ]; then
      IFS= read -r -t 1 line; rc=$?
      if [ "$rc" != 0 ]; then
        # Bash 3.2 returns 1 for both a timeout and end of input (bash 4+ returns >128 on timeout). The engine
        # writes $TMP/rc when it has exited: until then, silence is a timeout; after it, read the rest blocking.
        if [ "$rc" -gt 128 ] || [ ! -f "$TMP/rc" ]; then
          # No news for a second: show that we are alive, with the real elapsed time of this stage.
          [ -n "$CUR" ] && [ "$CUR" != downloading ] && draw_spin "$CUR_LABEL" "$(( $(date +%s) - STAGE_START ))"
          continue
        fi
        blocking=1; continue
      fi
    else
      IFS= read -r line || break
    fi
    case "$line" in
      '{"event": "progress"'*) ;;
      *) clear_line; printf '    %s%s%s\n' "$C_MUTED" "$line" "$RESET" >&2; continue ;;
    esac
    stage=$(json_str stage "$line")
    if [ "$stage" = downloading ]; then
      artifact=$(json_str artifactId "$line")
      done_b=$(json_num doneBytes "$line"); total=$(json_num totalBytes "$line")
      if [ "$CUR" != downloading ] || [ "$artifact" != "$CUR_LABEL" ]; then
        if [ "$CUR" = downloading ]; then [ "$FANCY" = 1 ] && ok "$T_DOWNLOADING $CUR_LABEL"; else finish_stage; fi
        CUR=downloading; CUR_LABEL=$artifact
        [ "$FANCY" = 1 ] || say "  $SYM_DOT $T_DOWNLOADING $artifact ($(mb "${total:-0}"))"
      fi
      draw_bar "$artifact" "${done_b:-0}" "${total:-0}"
      continue
    fi
    if [ "$CUR" = downloading ]; then [ "$FANCY" = 1 ] && ok "$T_DOWNLOADING $CUR_LABEL"; CUR=""; fi
    finish_stage
    if [ "$stage" = planned ]; then
      step 5 "$T_STEP5"; STEP5=1
      ok "$T_PLAN: $(json_str model "$line") $SYM_DOT $(json_str device "$line")"
      continue
    fi
    if [ "$STEP5" = 0 ] && { [ "$stage" = sealing ] || [ "$stage" = "done" ]; }; then step 5 "$T_STEP5"; STEP5=1; fi
    [ "$stage" = "done" ] && break
    CUR=$stage; CUR_LABEL=$(stage_label "$stage"); STAGE_START=$(date +%s)
    if [ "$FANCY" = 1 ]; then draw_spin "$CUR_LABEL"; else say "  $SYM_DOT $CUR_LABEL"; fi
  done
  clear_line
  cat >/dev/null  # drain, so the engine never blocks on a full pipe
}

muted "$T_RUN_HINT"
hide_cursor
{ "$BIN" quick --json --progress ${QUICK_ARGS[@]+"${QUICK_ARGS[@]}"} 2>&1 >"$TMP/summary.json"; echo $? >"$TMP/rc"; } | render
show_cursor
ENGINE_RC=$(cat "$TMP/rc" 2>/dev/null || echo 1)

# ---------------------------------------------------------------- summary card
# v0.1.4+ uses the shared macOS/Linux presenter: richer hardware and a private,
# opt-in browser result. Older pinned releases and test shims retain the original
# card below; the sealed benchmark evidence is never modified by the presenter.
S="$TMP/summary.json"
px() { plutil -extract "$1" raw -o - "$S" 2>/dev/null; }
pnum() { sed -n "s/^ *\"$1\": \\([^,]*\\),\\{0,1\\}$/\\1/p" "$S" | head -n 1; }
if [ ! -s "$S" ] || ! RUN_DIR=$(px runDirectory); then
  fail "$(printf "$T_NO_SUMMARY" "$ENGINE_RC")"
  exit "$ENGINE_RC"
fi
VIEW_ARGS=()
[ "$OPT_PLAIN" = 1 ] && VIEW_ARGS+=(--plain)
[ "$FANCY" = 1 ] && VIEW_ARGS+=(--ansi)
[ "$OPT_OPEN_RESULTS" = 1 ] && VIEW_ARGS+=(--open-results)
if "$BIN" evidence view "$RUN_DIR" --lang "$UI_LANG" ${VIEW_ARGS[@]+"${VIEW_ARGS[@]}"} >"$TMP/view.txt" 2>"$TMP/view.err" \
     && grep -q 'RIGROUTE.*AI BENCHMARK' "$TMP/view.txt"; then
  cat "$TMP/view.txt"
  SAFE=$(px uploadSafe)
  if [ "$OPT_QUIET" = 0 ]; then
    printf '  %s\n    open %s\n' "$T_NEXT_OPEN" "$(shell_path "$RUN_DIR")"
  fi
  if [ "$OPT_UPLOAD" = yes ] && [ "$SAFE" = READY ]; then
    say "  $T_UPLOAD_NOW"; "$BIN" upload "$RUN_DIR"; exit $?
  elif [ "$OPT_UPLOAD" != no ] && [ "$SAFE" = READY ] && [ "$OPT_QUIET" = 0 ]; then
    printf '    %s\n      %s upload %s\n' "$T_UPLOAD_HINT" "$(shell_path "$BIN")" "$(shell_path "$RUN_DIR")"
  fi
  exit "$ENGINE_RC"
fi
# Fall back to the earlier human-readable card if the new presenter is absent or
# cannot verify its input; no browser is opened on this fallback path.
OUTCOME=$(px outcome.status); FAILURE=$(px outcome.failure.message || true)
CAN_RUN=$(px canRun); USABLE=$(px usable); POLICY=$(px classifierPolicy); SAFE=$(px uploadSafe)
MODEL=$(px model || echo "-"); PROMPT=$(pnum promptTokensPerSecond); GEN=$(pnum generationTokensPerSecond)
case "$OUTCOME" in PASS) OC="$C_OK" ;; *) OC="$C_WARN" ;; esac
row() { printf '  %s%s%s %-12s %s\n' "$C_BRAND" "$CARD" "$RESET" "$1" "$2"; }
echo
printf '  %s%s%s %s%s%s\n' "$C_BRAND" "$CARD" "$RESET" "$BOLD" "RigRoute AI Benchmark $SYM_DOT $T_RESULT" "$RESET"
printf '  %s%s%s\n' "$C_BRAND" "$CARD" "$RESET"
row "$T_OUTCOME" "${OC}${OUTCOME}${RESET}${FAILURE:+ ($FAILURE)}"
row "CAN RUN" "$CAN_RUN"
row "USABLE" "$USABLE   ${C_MUTED}($POLICY)${RESET}"
row "$T_MODEL" "$MODEL"
case "$PROMPT" in ''|null|'"UNKNOWN"'|'"UNAVAILABLE"') ;; *) row "$T_PROMPT" "$PROMPT ${C_MUTED}$T_MEASURED${RESET}" ;; esac
case "$GEN" in ''|null|'"UNKNOWN"'|'"UNAVAILABLE"') ;; *) row "$T_GEN" "$GEN ${C_MUTED}$T_MEASURED${RESET}" ;; esac
row "$T_EVIDENCE" "$(tilde "$RUN_DIR")"
row "$T_UPLOADSAFE" "$SAFE"
if [ "$OPT_QUIET" = 0 ]; then
  echo
  printf '  %s%s%s\n' "$BOLD" "$T_NEXT" "$RESET"
  printf '    %s\n      open %s\n' "$T_NEXT_OPEN" "$(shell_path "$RUN_DIR")"
  printf '    %s\n      bash rigroute-benchmark-macos.sh\n' "$T_NEXT_AGAIN"
fi
if [ "$OPT_UPLOAD" = yes ] && [ "$SAFE" = READY ]; then
  echo; say "  $T_UPLOAD_NOW"
  "$BIN" upload "$RUN_DIR"
  exit $?
elif [ "$OPT_UPLOAD" != no ] && [ "$SAFE" = READY ] && [ "$OPT_QUIET" = 0 ]; then
  printf '    %s\n      %s upload %s\n' "$T_UPLOAD_HINT" "$(shell_path "$BIN")" "$(shell_path "$RUN_DIR")"
fi
exit "$ENGINE_RC"
