#!/bin/sh
# Tracetoon launcher. Finds a way to run Tracetoon without a separate install:
#   1. $TRACETOON_BIN
#   2. a binary shipped next to this script, or cached from an earlier download
#   3. bun or node (22+) running the bundled dist/tracetoon.mjs
#   4. with TRACETOON_ALLOW_DOWNLOAD=1: download the release binary with gh,
#      verify its SHA-256 against checksums.txt, cache it
# Exits 3 when none of these work, so the skill can fall back to manual mode.
set -eu

here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
skill=$(dirname -- "$here")
ver=$(cat "$skill/VERSION" 2>/dev/null || echo 0.0.0)
# Fonts and the rasterizer live in the skill; a cached binary can't find them alone.
TRACETOON_ASSETS="${TRACETOON_ASSETS:-$skill/assets}"
export TRACETOON_ASSETS
TRACETOON_LAUNCHER="$here/tracetoon"
export TRACETOON_LAUNCHER

build=$(sed -n 's/.*"buildId"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$skill/build.json" 2>/dev/null || true)
if [ -z "$build" ]; then
  # Build outputs aren't committed: a source checkout has no build.json until it is built.
  echo 'tracetoon: this copy has no build (no build.json; a source checkout?). Run `bun run bundle` to build it, or `bun src/cli.ts` from the checkout. Installed with a skills tool? Reinstall from the release branch: npx skills add Tracetoon/tracetoon#release, or gh skill install Tracetoon/tracetoon plugin/skills/tracetoon --pin release.' >&2
  exit 3
fi
matches() {
  [ -n "$build" ] || return 1
  info=$("$@" build-info --json 2>/dev/null) || return 1
  compact=$(printf '%s' "$info" | tr -d ' \r\n')
  case "$compact" in *"\"buildId\":\"$build\""*) return 0 ;; *) return 1 ;; esac
}
if [ -n "${TRACETOON_BIN:-}" ]; then
  matches "$TRACETOON_BIN" || { echo 'tracetoon: explicit runtime does not match this skill build; run `tracetoon update` (or re-run the installer).' >&2; exit 3; }
  exec "$TRACETOON_BIN" "$@"
fi

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  MINGW* | MSYS* | CYGWIN*) os=windows ;;
  *) os=unknown ;;
esac
case "$(uname -m)" in
  arm64 | aarch64) arch=arm64 ;;
  x86_64 | amd64) arch=x64 ;;
  *) arch=unknown ;;
esac
plat="$os-$arch"
exe=""
[ "$os" = windows ] && exe=".exe"
name="tracetoon-$plat$exe"
cache="${XDG_CACHE_HOME:-$HOME/.cache}/tracetoon/$ver"

# Where the installer puts the binary (a fixed path, so hooks survive updates).
installed="${XDG_DATA_HOME:-$HOME/.local/share}/tracetoon/bin/tracetoon$exe"
win_cache=""
if [ "$os" = windows ] && [ -n "${LOCALAPPDATA:-}" ] && command -v cygpath >/dev/null 2>&1; then
  installed="$(cygpath -u "$LOCALAPPDATA")/tracetoon/bin/tracetoon.exe"
  win_cache="$(cygpath -u "$LOCALAPPDATA")/tracetoon/cache/$ver/$name"
fi
for candidate in "$here/$name" "$installed" "$cache/$name" $win_cache; do
  if [ -x "$candidate" ] && matches "$candidate"; then exec "$candidate" "$@"; fi
done

bundle="$skill/dist/tracetoon.mjs"
if [ -f "$bundle" ]; then
  if command -v bun >/dev/null 2>&1 && matches bun "$bundle"; then exec bun "$bundle" "$@"; fi
  if command -v node >/dev/null 2>&1; then
    major=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)
    if [ "$major" -ge 22 ] && matches node "$bundle"; then exec node "$bundle" "$@"; fi
  fi
fi

if [ "${TRACETOON_ALLOW_DOWNLOAD:-}" = 1 ] && command -v gh >/dev/null 2>&1; then
  tmp=$(mktemp -d)
  if gh release download "v$ver" -R Tracetoon/tracetoon -p "$name" -D "$tmp" >/dev/null 2>&1; then
    # Prefer a checksum pinned in the skill; otherwise use the release's own list.
    want=$(grep " $name\$" "$skill/checksums.txt" 2>/dev/null | cut -d' ' -f1 || true)
    if [ -z "$want" ] && gh release download "v$ver" -R Tracetoon/tracetoon -p checksums.txt -D "$tmp" >/dev/null 2>&1; then
      want=$(grep " $name\$" "$tmp/checksums.txt" | cut -d' ' -f1 || true)
    fi
    if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$tmp/$name" | cut -d' ' -f1)
    else got=$(shasum -a 256 "$tmp/$name" | cut -d' ' -f1); fi
    if [ -n "$want" ] && [ "$want" = "$got" ]; then
      mkdir -p "$cache"
      mv "$tmp/$name" "$cache/$name"
      chmod +x "$cache/$name"
      rm -rf "$tmp"
      if matches "$cache/$name"; then exec "$cache/$name" "$@"; fi
      echo 'tracetoon: downloaded runtime does not match the skill build; update both.' >&2
      exit 3
    fi
    echo "tracetoon: downloaded binary failed its checksum; not running it." >&2
  fi
  rm -rf "$tmp"
fi

echo 'tracetoon: no matching runtime for this skill build. Run `tracetoon update` (or re-run the installer) to bring the skill and runtime together, or use Bun/Node 22+ with its matching bundle.' >&2
echo "tracetoon: set TRACETOON_ALLOW_DOWNLOAD=1 to fetch the release binary with gh." >&2
exit 3
