#!/bin/sh
# jevcache installer — downloads a single static binary. No runtime required.
#   curl -fsSL jevcache.sh/install | sh
set -e

BASE="${JEVCACHE_BASE:-https://jevcache.sh}"
os=$(uname -s)
arch=$(uname -m)
case "$os" in
  Darwin) o=darwin ;;
  Linux)  o=linux ;;
  *) echo "jevcache: unsupported OS '$os'. See $BASE" >&2; exit 1 ;;
esac
case "$arch" in
  arm64|aarch64) a=arm64 ;;
  x86_64|amd64)  a=x64 ;;
  *) echo "jevcache: unsupported architecture '$arch'." >&2; exit 1 ;;
esac
name="jevcache-$o-$a"
url="$BASE/bin/$name"

# pick a writable bin dir on PATH, else ~/.local/bin
BIN=""
for d in "$HOME/.local/bin" "/usr/local/bin"; do
  if [ -d "$d" ] && [ -w "$d" ]; then BIN="$d"; break; fi
done
[ -z "$BIN" ] && BIN="$HOME/.local/bin"
mkdir -p "$BIN"

tmp=$(mktemp)
echo "downloading $name..."
curl -fsSL "$url" -o "$tmp"

# verify checksum
want=$(curl -fsSL "$url.sha256" 2>/dev/null | awk '{print $1}')
if [ -n "$want" ]; then
  if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$tmp" | awk '{print $1}');
  else got=$(sha256sum "$tmp" | awk '{print $1}'); fi
  if [ "$want" != "$got" ]; then echo "jevcache: checksum mismatch — aborting." >&2; rm -f "$tmp"; exit 1; fi
fi

chmod +x "$tmp"
mv "$tmp" "$BIN/jevcache"
# anonymous install counter (best-effort, no data collected beyond a bump)
curl -fsS -m3 "$BASE/api/event/install" >/dev/null 2>&1 || true
echo "installed jevcache → $BIN/jevcache"
case ":$PATH:" in
  *":$BIN:"*) : ;;
  *) echo "note: add $BIN to your PATH:  export PATH=\"$BIN:\$PATH\"" ;;
esac
"$BIN/jevcache" version >/dev/null 2>&1 && echo "run 'jevcache' to get started." || true
