#!/bin/sh
set -eu

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux)  os=linux ;;
  *) echo "error: unsupported OS ($(uname -s)); only macOS and Linux are supported" >&2; exit 1 ;;
esac

case "$(uname -m)" in
  x86_64|amd64)  arch=x64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) echo "error: unsupported architecture ($(uname -m)); only x64 and arm64 are supported" >&2; exit 1 ;;
esac

asset="krei-${os}-${arch}"
BASE="${KREI_INSTALL_BASE:-https://krei.ai/dl}"
url="${BASE}/${asset}"

if [ "${KREI_INSTALL_DRY_RUN:-0}" = "1" ]; then
  echo "os=${os}"
  echo "arch=${arch}"
  echo "asset=${asset}"
  echo "url=${url}"
  exit 0
fi

if ! command -v curl >/dev/null 2>&1; then
  echo "error: curl is required but not installed" >&2
  exit 1
fi

DIR="${KREI_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$DIR"

tmp="$(mktemp)"
sums="$(mktemp)"
trap 'rm -f "$tmp" "$sums"' EXIT

# ponytail: SHA256SUMS ships beside the binary, so this catches corruption and asset/sums drift,
# not a compromised release — that needs a signature verified against an out-of-band key.
if ! curl -fsSL "${BASE}/SHA256SUMS" -o "$sums"; then
  echo "error: failed to download ${BASE}/SHA256SUMS" >&2
  exit 1
fi

# SHA256SUMS lines must use bare asset names ("krei-linux-x64", not "./krei-linux-x64").
expected="$(awk -v n="$asset" '$2 == n || $2 == "*"n { print $1; exit }' "$sums")"
if [ -z "$expected" ]; then
  echo "error: no checksum found for $asset in SHA256SUMS" >&2
  exit 1
fi

if ! curl -fsSL "$url" -o "$tmp"; then
  echo "error: failed to download $url" >&2
  exit 1
fi

if command -v sha256sum >/dev/null 2>&1; then
  actual="$(sha256sum "$tmp" | awk '{ print $1 }')"
elif command -v shasum >/dev/null 2>&1; then
  actual="$(shasum -a 256 "$tmp" | awk '{ print $1 }')"
else
  echo "error: neither sha256sum nor shasum is available" >&2
  exit 1
fi

if [ "$actual" != "$expected" ]; then
  echo "error: checksum mismatch for $asset (expected $expected, got $actual)" >&2
  exit 1
fi

chmod +x "$tmp"
mv "$tmp" "$DIR/krei"

# Codegraph grammar assets (optional ride-along): the symbol index reads these
# from $DIR/krei-wasm/ beside the binary. Best-effort by design — a release
# without the tarball, or a box without tar(1), still installs a working krei
# whose index simply stays off for now (re-run the installer after a release
# that ships it).
if curl -fsSL "${BASE}/krei-wasm.tar.gz" -o "${tmp}.wasm-tgz" 2>/dev/null; then
  if tar -xzf "${tmp}.wasm-tgz" -C "$DIR" 2>/dev/null; then
    echo "codegraph: grammar assets installed to $DIR/krei-wasm"
  fi
fi
rm -f "${tmp}.wasm-tgz"

case ":${PATH}:" in
  *":${DIR}:"*) ;;
  *) echo "note: '$DIR' is not on your PATH. Add it: export PATH=\"$DIR:\$PATH\"" ;;
esac

echo "installed: $DIR/krei"
