#!/bin/sh
# ns-brain installer
# Usage: curl -fsSL https://brain.fightclub.pro/install.sh | sh
set -e

BASE_URL="https://brain.fightclub.pro/dl"
# Fail closed. This used to fall back to a hardcoded version, which went stale the moment
# the next release shipped: an installer that cannot reach the version file would silently
# put a client older than the schema most stores are on, and that client then refuses to
# open them. No answer is better than a wrong one.
VERSION="${NS_BRAIN_VERSION:-$(curl -fsSL "https://brain.fightclub.pro/latest-version.txt" 2>/dev/null || true)}"
VERSION="$(printf '%s' "$VERSION" | tr -d '[:space:]')"
if [ -z "$VERSION" ]; then
  echo "  x Cannot reach https://brain.fightclub.pro/latest-version.txt to find out which"
  echo "    version to install, and refusing to guess: an old client will not open a newer"
  echo "    store. Check your connection, or set NS_BRAIN_VERSION=<version> to pin one."
  exit 1
fi

detect_platform() {
  OS=$(uname -s | tr '[:upper:]' '[:lower:]')
  ARCH=$(uname -m)

  case "$OS" in
    linux)  OS="linux" ;;
    darwin) OS="darwin" ;;
    mingw*|msys*|cygwin*) OS="windows" ;;
    *) echo "Unsupported OS: $OS"; exit 1 ;;
  esac

  case "$ARCH" in
    x86_64|amd64)  ARCH="amd64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    armv7l|armv6l) ARCH="arm" ;;
    i386|i686)     ARCH="386" ;;
    *) echo "Unsupported architecture: $ARCH"; exit 1 ;;
  esac

  echo "${OS}/${ARCH}"
}

main() {
  PLATFORM=$(detect_platform)
  OS="${PLATFORM%/*}"
  ARCH="${PLATFORM#*/}"

  BINARY="ns-brain-${OS}-${ARCH}"
  [ "$OS" = "windows" ] && BINARY="${BINARY}.exe"

  URL="${BASE_URL}/${VERSION}/${BINARY}"
  INSTALL_DIR="/usr/local/bin"
  TARGET="${INSTALL_DIR}/ns-brain"

  echo ""
  echo "  ns-brain installer v${VERSION}"
  echo "  --------------------------------"
  echo "  Platform:  ${OS}/${ARCH}"
  echo "  Binary:    ${BINARY}"
  echo ""

  TMP=$(mktemp)
  echo "  -> Downloading..."
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$URL" -o "$TMP"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$TMP" "$URL"
  else
    echo "  x Neither curl nor wget found"; exit 1
  fi

  # Verify before installing, and refuse when we cannot. A brain holds the reasoning behind
  # your decisions, and `ns-brain upgrade` already refuses an unverified binary; an installer
  # that skipped the check whenever the sums file, a hash tool or the platform's line was
  # missing would be the one path that installs whatever it was handed.
  SUMS=$(curl -fsSL "${BASE_URL}/${VERSION}/SHA256SUMS" 2>/dev/null || true)
  if [ -z "$SUMS" ]; then
    rm -f "$TMP"
    echo "  x Could not fetch the checksum file for ${VERSION}. Refusing to install an unverified binary."
    exit 1
  fi
  if command -v sha256sum >/dev/null 2>&1; then
    GOT=$(sha256sum "$TMP" | cut -d' ' -f1)
  elif command -v shasum >/dev/null 2>&1; then
    GOT=$(shasum -a 256 "$TMP" | cut -d' ' -f1)
  else
    rm -f "$TMP"
    echo "  x Neither sha256sum nor shasum found, so the download cannot be verified. Install one and rerun."
    exit 1
  fi
  WANT=$(echo "$SUMS" | grep " ${BINARY}\$" | cut -d' ' -f1 || true)
  if [ -z "$WANT" ]; then
    rm -f "$TMP"
    echo "  x The checksum file for ${VERSION} does not list ${BINARY}. Refusing to install it."
    exit 1
  fi
  if [ "$GOT" != "$WANT" ]; then
    rm -f "$TMP"
    echo "  x Checksum mismatch for ${BINARY}."
    echo "    expected ${WANT}"
    echo "    got      ${GOT}"
    exit 1
  fi
  echo "  -> Checksum verified"

  chmod +x "$TMP"

  if [ -w "$INSTALL_DIR" ]; then
    mv "$TMP" "$TARGET"
  else
    echo "  -> Installing to ${INSTALL_DIR} (requires sudo)..."
    sudo mv "$TMP" "$TARGET"
  fi

  echo "  ok Installed to ${TARGET}"
  echo ""
  echo "  Get started, inside a project:"
  echo "    ns-brain init                 # create the brain and wire the hooks"
  echo "    ns-brain bootstrap            # seed it from past sessions"
  echo "    ns-brain recall \"<topic>\"     # ask it something"
  echo ""
  echo "  Nothing leaves your machine. There is no account and no telemetry."
  echo ""
}

main
