#!/bin/sh
# Board Connect CLI installer (curl -fsSL https://dev.board.fun/connect/install | sh)
#
# Detects platform, downloads the matching binary to ~/.local/bin/board-connect,
# and prints a PATH hint if needed.
#
# POSIX sh — no bashisms, so `| sh` works under dash/ash/bash alike.
set -eu

case "$(uname -s)-$(uname -m)" in
  Darwin-arm64|Darwin-x86_64)  ASSET="board-connect-darwin-universal" ;;
  Linux-x86_64)   ASSET="board-connect-linux-amd64" ;;
  Linux-aarch64)  ASSET="board-connect-linux-arm64" ;;
  *)
    echo "Unsupported platform: $(uname -s)-$(uname -m)" >&2
    exit 1
    ;;
esac

VERSION=$(curl -fsSL https://dev.board.fun/connect/latest.txt)
URL="https://dev.board.fun/connect/${VERSION}/${ASSET}"
SUMS_URL="https://dev.board.fun/connect/${VERSION}/SHA256SUMS"
BIN_DIR="$HOME/.local/bin"

mkdir -p "$BIN_DIR"

# Download to a temp file first so a failed checksum never leaves a runnable binary in place.
TMP_BIN=$(mktemp "${TMPDIR:-/tmp}/board-connect.XXXXXX")
TMP_SUMS=$(mktemp "${TMPDIR:-/tmp}/board-connect-sums.XXXXXX")
cleanup() { rm -f "$TMP_BIN" "$TMP_SUMS"; }
trap cleanup EXIT

curl -fsSL "$URL" -o "$TMP_BIN"

# Verify the download against the published SHA256SUMS manifest. This is fail-closed:
# the manifest is required, and a mismatch (or a missing entry) aborts before install.
curl -fsSL "$SUMS_URL" -o "$TMP_SUMS"

EXPECTED=$(awk -v a="$ASSET" '$2 == a { print $1 }' "$TMP_SUMS")
if [ -z "$EXPECTED" ]; then
  echo "Checksum verification failed: no entry for $ASSET in SHA256SUMS." >&2
  exit 1
fi

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

if [ "$ACTUAL" != "$EXPECTED" ]; then
  echo "Checksum mismatch for $ASSET:" >&2
  echo "  expected: $EXPECTED" >&2
  echo "  actual:   $ACTUAL" >&2
  exit 1
fi

mv "$TMP_BIN" "$BIN_DIR/board-connect"
trap - EXIT
rm -f "$TMP_SUMS"
chmod +x "$BIN_DIR/board-connect"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    echo
    echo "$BIN_DIR is not on your PATH. Add this to your shell rc file:"
    echo "  export PATH=\"\$HOME/.local/bin:\$PATH\""
    ;;
esac

echo "Installed Board Connect $VERSION."
echo "Run: board-connect"
