#!/bin/sh
# TokenOtter installer: downloads the binary for this machine from the latest release,
# checks its SHA-256, and installs it to ~/.local/bin (or $TOKENOTTER_BIN_DIR).
set -eu
BIN_DIR="${TOKENOTTER_BIN_DIR:-$HOME/.local/bin}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in darwin|linux) ;; *) echo "tokenotter: unsupported OS $os (Windows: download tokenotter_windows_amd64.exe from https://www.tokenotter.com/download/tokenotter_windows_amd64.exe)" >&2; exit 1 ;; esac
arch=$(uname -m)
case "$arch" in x86_64|amd64) arch=amd64 ;; arm64|aarch64) arch=arm64 ;; *) echo "tokenotter: unsupported CPU $arch" >&2; exit 1 ;; esac

name="tokenotter_${os}_${arch}"
base="https://www.tokenotter.com/download"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

echo "Downloading $name ..."
curl -fsSL "$base/$name" -o "$tmp/$name"
curl -fsSL "$base/checksums.txt" -o "$tmp/checksums.txt"

want=$(grep " $name\$" "$tmp/checksums.txt" | cut -d' ' -f1)
if command -v shasum >/dev/null 2>&1; then got=$(shasum -a 256 "$tmp/$name" | cut -d' ' -f1); else got=$(sha256sum "$tmp/$name" | cut -d' ' -f1); fi
if [ -z "$want" ] || [ "$want" != "$got" ]; then echo "tokenotter: checksum mismatch, not installing" >&2; exit 1; fi

mkdir -p "$BIN_DIR"
install -m 0755 "$tmp/$name" "$BIN_DIR/tokenotter"
echo "Installed $BIN_DIR/tokenotter"
case ":$PATH:" in *":$BIN_DIR:"*) ;; *) echo "Add $BIN_DIR to your PATH to run tokenotter by name." ;; esac
echo "Next: tokenotter init --budget 5 && tokenotter serve"
echo "Link the MCP server: claude mcp add tokenotter -- $BIN_DIR/tokenotter mcp"
