#!/bin/sh
# Balladeer thin-client installer (central-served; decision_433e2108).
# Downloads the CLI, verifies its checksum, installs it, then tells you how to pair.
set -eu

BASE="https://get.balladeer.ai"
TGZ_URL="$BASE/install/client.tgz"
SHA_URL="$BASE/install/client.tgz.sha256"

echo "Installing the Balladeer client from $BASE"

if ! command -v node >/dev/null 2>&1; then
  echo "error: Node.js is required (v20+). Install it from https://nodejs.org and re-run." >&2
  exit 1
fi
if ! command -v npm >/dev/null 2>&1; then
  echo "error: npm is required (it ships with Node.js)." >&2
  exit 1
fi

fetch() {
  # $1 url, $2 out. curl if present, else wget.
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2";
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1";
  else echo "error: need curl or wget." >&2; exit 1; fi
}

TMP="$(mktemp -d 2>/dev/null || mktemp -d -t balladeer)"
trap 'rm -rf "$TMP"' EXIT
TGZ="$TMP/balladeer-client.tgz"

fetch "$TGZ_URL" "$TGZ"
fetch "$SHA_URL" "$TMP/sha"

# Verify the checksum BEFORE running anything from the tarball (npm executes package scripts).
EXPECTED="$(awk '{print $1}' "$TMP/sha")"
if command -v sha256sum >/dev/null 2>&1; then ACTUAL="$(sha256sum "$TGZ" | awk '{print $1}')";
elif command -v shasum >/dev/null 2>&1; then ACTUAL="$(shasum -a 256 "$TGZ" | awk '{print $1}')";
else echo "error: need sha256sum or shasum to verify the download." >&2; exit 1; fi
if [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "error: checksum mismatch; refusing to install a tampered download." >&2
  echo "  expected $EXPECTED" >&2
  echo "  actual   $ACTUAL" >&2
  exit 1
fi

echo "Checksum OK. Installing globally with npm…"
# --ignore-scripts: the client has no install hooks, and this keeps a compromised tarball from
# running arbitrary lifecycle scripts even after the checksum gate.
npm install -g --ignore-scripts "$TGZ"

echo ""
echo "Balladeer is installed. Pair this machine with the token from your setup page:"
echo "  balladeer login --token <your-token> --server $BASE"
