#!/bin/sh
# Anteriora installer — 0.9.124
#
#   curl -LsSf https://inferroute.ai/install-anteriora.sh | sh
#
# What it does, and all it does:
#   1. installs `uv` if there is none (it brings its own Python; your system Python is not touched);
#   2. makes a private environment in ~/anteriora (or keeps using ~/probant, from an install made before the
#      product was renamed);
#   3. downloads Anteriora 0.9.124 — and on an Apple-silicon Mac its protected virtual machine — together with
#      the exact list of every library it needs, checks each file against the fingerprint written into this
#      script, and installs them there. Libraries are installed ONLY if they match that list byte for byte, so
#      two installs of this version are the same program, today and in a year;
#   4. sets up patent search from InferRoute's published, signed files (re-checked each time Anteriora starts);
#   5. prints the next command.
# It does not use sudo, edit your shell profile, or install anything outside ~/anteriora, ~/.local/bin (uv, and a
# link named `anteriora`) and uv's own Python folder. To remove it all:
#   rm -rf ~/anteriora ~/Anteriora ~/.inferroute ~/.local/bin/anteriora
#
# The fingerprints below are what make this script fetch exactly the files we released. What makes the
# virtual machine trustworthy is separate: Anteriora itself refuses to start it unless its files carry
# InferRoute's signature.
set -eu

VERSION="0.9.124"
BASE="${IR_INSTALL_BASE:-https://inferroute.ai/client}"
CLIENT_FILE="inferroute-0.9.124-py3-none-any.whl"
CLIENT_SHA256="44c79057f4c6c12a9a575cd9894fd23d22badb6d64f3a9f8a6f2393cccb10e63"
RUNTIME_FILE="inferroute_macos_vm_runtime-0.9.124-py3-none-macosx_11_0_arm64.whl"
RUNTIME_SHA256="c1d1fac56b532959953d3e2f3e6a9f758660e5ab45be3bb263991804dfaf4313"
LOCK_FILE="inferroute-0.9.124-lock.txt"
LOCK_SHA256="2535be883206d74acd706569de1cba05623dca3d43454420b11445fb51176841"
# ~/anteriora for a new install. An environment made by an earlier installer, when the product was called Probant,
# is in ~/probant: keep using it (and updating it) rather than leave a second copy behind.
if [ -n "${ANTERIORA_HOME:-}" ]; then TARGET="$ANTERIORA_HOME"
elif [ -n "${PROBANT_HOME:-}" ]; then TARGET="$PROBANT_HOME"
elif [ ! -e "$HOME/anteriora" ] && [ -x "$HOME/probant/bin/python" ] && [ -x "$HOME/probant/bin/probant" ]; then TARGET="$HOME/probant"
else TARGET="$HOME/anteriora"
fi

say()  { printf '%s\n' "$*"; }
# What this computer is, in one line: the processor (uname -m) and the system version. It is printed when the install ends
# or stops, so the person can send it back with their public key. Nothing is sent from here.
machine_line() {
  M=$(uname -m 2>/dev/null || echo unknown)
  if command -v sw_vers >/dev/null 2>&1; then V="macOS $(sw_vers -productVersion 2>/dev/null)"; else V=$(uname -sr 2>/dev/null); fi
  printf '%s · %s' "$M" "$V"
}
stop() { printf '\n  Anteriora was not installed: %s\n  This computer: %s\n\n' "$*" "$(machine_line)" >&2; exit 1; }

OS=$(uname -s); ARCH=$(uname -m)
NEEDS_VM=no
case "$OS" in
  Darwin)
    [ "$ARCH" = "arm64" ] || stop "this Mac has an Intel processor. Anteriora on a Mac needs Apple silicon (M1 or later)."
    NEEDS_VM=yes ;;
  Linux) ;;
  *) stop "this installer supports macOS (Apple silicon) and Linux. For Windows, ask InferRoute." ;;
esac
command -v curl >/dev/null 2>&1 || stop "curl was not found."

# ── uv ──────────────────────────────────────────────────────────────────────────────────────────────────────
UV=""
for c in "$(command -v uv 2>/dev/null || true)" "$HOME/.local/bin/uv"; do
  [ -n "$c" ] && [ -x "$c" ] && { UV="$c"; break; }
done
if [ -z "$UV" ]; then
  say "Installing uv (a Python installer; it keeps its own Python, apart from the system's) ..."
  curl -LsSf https://astral.sh/uv/install.sh | sh >/dev/null 2>&1 || stop "could not install uv. Check the connection and run this again."
  UV="$HOME/.local/bin/uv"
  [ -x "$UV" ] || stop "uv did not install where expected ($UV)."
fi

# ── the files, checked before they are used ──────────────────────────────────────────────────────────────────
WORK=$(mktemp -d "${TMPDIR:-/tmp}/anteriora-install.XXXXXX")
trap 'rm -rf "$WORK"' EXIT INT TERM
sha() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1; else sha256sum "$1" | cut -d' ' -f1; fi; }
fetch() {   # name expected-sha256
  say "Downloading $1 ..."
  # A dropped connection resumes where it stopped (-C -) rather than starting a 69 MB file again: on a weak link
  # one failure in a single pass used to mean the whole install failed. The fingerprint below is still what decides.
  tries=0
  until curl -fL --retry 3 --retry-delay 2 -C - --progress-bar -o "$WORK/$1" "$BASE/$1"; do
    [ -f "$WORK/$1" ] && [ "$(sha "$WORK/$1")" = "$2" ] && break          # it was whole; only the close failed
    tries=$((tries + 1))
    [ "$tries" -ge 6 ] && stop "could not download $BASE/$1"
    say "  the connection dropped; continuing from where it stopped ..."
    sleep 2
  done
  [ "$(sha "$WORK/$1")" = "$2" ] || stop "$1 does not match the fingerprint in this installer. Nothing was installed. Please tell InferRoute."
}
fetch "$CLIENT_FILE" "$CLIENT_SHA256"
fetch "$LOCK_FILE" "$LOCK_SHA256"
[ "$NEEDS_VM" = "yes" ] && fetch "$RUNTIME_FILE" "$RUNTIME_SHA256"

# ── the environment ──────────────────────────────────────────────────────────────────────────────────────────
if [ -e "$TARGET" ] && [ ! -x "$TARGET/bin/python" ]; then
  stop "$TARGET exists and is not an Anteriora environment. Move it aside, or set ANTERIORA_HOME to another folder."
fi
say "Setting up $TARGET ..."
"$UV" venv --quiet --allow-existing --python 3.12 "$TARGET" || stop "could not create the environment."
# 1. every library, from the pinned list, each refused unless its hash matches. 2. Anteriora itself and, on a Mac,
# its virtual machine, WITHOUT letting the installer choose anything: they were fingerprinted above.
"$UV" pip install --quiet --python "$TARGET/bin/python" --require-hashes -r "$WORK/$LOCK_FILE" \
  || stop "a library did not match its pinned fingerprint, or could not be fetched. Nothing was installed. The messages above say which."
if [ "$NEEDS_VM" = "yes" ]; then
  "$UV" pip install --quiet --python "$TARGET/bin/python" --no-deps "$WORK/$CLIENT_FILE" "$WORK/$RUNTIME_FILE" \
    || stop "the install failed. The messages above say why."
else
  "$UV" pip install --quiet --python "$TARGET/bin/python" --no-deps "$WORK/$CLIENT_FILE" \
    || stop "the install failed. The messages above say why."
fi
# The program that now exists must be exactly the one this script names — not whatever an older install left.
GOT=$("$TARGET/bin/ir" --version 2>/dev/null | awk '{print $NF}')
[ "$GOT" = "$VERSION" ] || stop "the installed program reports version '${GOT:-nothing}', not $VERSION."

# Patent search: fetch InferRoute's signed reference and where the search machine is, and write the
# configuration. Anteriora checks the reference's signature against a key built into the program. If this
# fails (no connection, say) the install is still good: Anteriora tries again every time it starts.
say "Setting up patent search ..."
"$TARGET/bin/ir" probant setup-search 2>&1 | sed 's/^/  /' || true

# Another `ir` earlier on PATH is common (an older install). Anteriora never uses it — it runs its own — but a person
# typing `ir` would, so say so rather than let two versions answer to one name.
OTHER=$(command -v ir 2>/dev/null || true)
if [ -n "$OTHER" ] && [ "$OTHER" != "$TARGET/bin/ir" ]; then
  say ""
  say "  Note: typing just  ir  here runs a different program ($OTHER, $("$OTHER" --version 2>/dev/null | awk '{print $NF}')),"
  say "        not this one. Use the full path shown below; Anteriora itself always uses its own."
fi

# A bare `anteriora` command: a link in ~/.local/bin, where uv already lives. It is made only when nothing else is
# there (or what is there is already a link), so a program of the same name is never overwritten.
LINK_DIR="$HOME/.local/bin"
LINKED=no
if [ -x "$TARGET/bin/anteriora" ] && mkdir -p "$LINK_DIR" 2>/dev/null; then
  if [ ! -e "$LINK_DIR/anteriora" ] || [ -L "$LINK_DIR/anteriora" ]; then
    ln -sf "$TARGET/bin/anteriora" "$LINK_DIR/anteriora" 2>/dev/null && LINKED=yes
  fi
  # `probant`, the earlier name, keeps working for people who learned it — but it is only ever ADDED where
  # nothing of that name exists. A `probant` link to some other install is left alone.
  if [ -x "$TARGET/bin/probant" ] && [ ! -e "$LINK_DIR/probant" ] && [ ! -L "$LINK_DIR/probant" ]; then
    ln -s "$TARGET/bin/probant" "$LINK_DIR/probant" 2>/dev/null || true
  fi
fi

say ""
say "Anteriora $VERSION is installed."
say ""
say "  This computer:       $(machine_line)"
say "                       (copy this line and send it back with your public key)"
say ""
if [ "$LINKED" = "yes" ]; then
  say "  Start it:            anteriora          (in a new Terminal window; it will ask for your InferRoute key first)"
  say "                       If your Terminal says 'command not found', run $TARGET/bin/anteriora"
  say "  Your public key:     anteriora identity"
else
  say "  Start it:            $TARGET/bin/anteriora   (it will ask for your InferRoute key first)"
  say "  Your public key:     $TARGET/bin/anteriora identity"
fi
say ""
