#!/bin/bash
# Hindsight installer — https://hindsight.technology
#
# Installs one small binary, the launcher, to ~/.local/share/hindsight/bin/hindsight (linked from
# ~/.local/bin/hindsight) and runs it. The launcher downloads the engine, verifies its checksum, keeps it
# current in the background, and serves the app at http://localhost:4747. Everything runs on your machine:
# no account, and analysis goes through your own claude / codex CLI.
set -euo pipefail

MANIFEST_URL="${HINDSIGHT_MANIFEST:-https://github.com/dsiroker/hindsight-releases/releases/latest/download/latest.json}"
NO_RUN="${HINDSIGHT_NO_RUN:-}"

if [ "$(id -u)" = "0" ] && [ -n "${SUDO_USER:-}" ]; then
  echo "Please run without sudo: everything installs under your home directory." >&2; exit 1
fi

os="$(uname -s)"; arch="$(uname -m)"
case "$os" in
  Darwin) platform="darwin" ;;
  Linux) platform="linux" ;;
  *) echo "Unsupported OS: $os (macOS and Linux for now; Windows via WSL)" >&2; exit 1 ;;
esac
case "$arch" in
  arm64|aarch64) cpu="arm64" ;;
  x86_64|amd64) cpu="x64" ;;
  *) echo "Unsupported CPU: $arch" >&2; exit 1 ;;
esac
target="$platform-$cpu"

command -v curl >/dev/null 2>&1 || { echo "missing curl" >&2; exit 1; }
sha() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'; else sha256sum "$1" | awk '{print $1}'; fi; }

echo "→ Fetching the latest release…"
manifest="$(curl -fsSL "$MANIFEST_URL")"
flat="$(printf '%s' "$manifest" | tr -d '\n ')"
# The launcher block of the manifest, then this target's entry inside it.
launcher="$(printf '%s' "$flat" | sed -n 's/.*"launcher":{\(.*\)$/\1/p')"
version="$(printf '%s' "$launcher" | sed -n 's/^"version":"\([^"]*\)".*/\1/p')"
block="$(printf '%s' "$launcher" | sed -n 's/.*"'"$target"'":{\([^}]*\)}.*/\1/p')"
url="$(printf '%s' "$block" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p')"
sum="$(printf '%s' "$block" | sed -n 's/.*"sha256":"\([0-9a-f]*\)".*/\1/p')"
[ -n "$version" ] && [ -n "$url" ] && [ -n "$sum" ] || { echo "No launcher build for $target in the manifest" >&2; exit 1; }

base="${XDG_DATA_HOME:-$HOME/.local/share}/hindsight"
bin="$base/bin/hindsight"
mkdir -p "$base/bin" "$HOME/.local/bin"
if [ ! -x "$bin" ] || [ "$(sha "$bin")" != "$sum" ]; then
  echo "→ Downloading hindsight launcher $version for ${target}…"
  tmp="$(mktemp "$base/bin/.download.XXXXXX")"
  curl -fL --progress-bar "$url" -o "$tmp"
  got="$(sha "$tmp")"
  [ "$got" = "$sum" ] || { echo "Checksum mismatch (expected $sum, got $got)" >&2; rm -f "$tmp"; exit 1; }
  chmod +x "$tmp"
  if [ "$platform" = "darwin" ]; then xattr -d com.apple.quarantine "$tmp" 2>/dev/null || true; fi
  mv -f "$tmp" "$bin"
fi
ln -sfn "$bin" "$HOME/.local/bin/hindsight"
echo "✓ Installed hindsight → ~/.local/bin/hindsight (launcher $version)"

case ":$PATH:" in
  *":$HOME/.local/bin:"*) ;;
  *) echo "  Add to your PATH:  export PATH=\"\$HOME/.local/bin:\$PATH\"" ;;
esac

if [ -z "$NO_RUN" ] && [ -t 1 ]; then
  exec "$bin"
fi
