#!/bin/sh
# Mnema installer — one shared, verified memory for every local LLM/agent.
#
#   curl -fsSL https://mnema.zimac.ai/install.sh | sh
#
# Downloads the headless `mnema` binary for this OS/arch from the release
# bucket, verifies its published SHA-256, and installs it into
# $MNEMA_INSTALL_DIR (default ~/.local/bin). No root required.
set -eu

BASE="${MNEMA_DIST_BASE:-https://mnema.zimac.ai/dist}"
DIR="${MNEMA_INSTALL_DIR:-$HOME/.local/bin}"

os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Darwin) file="mnema-macos-universal.tar.gz" ;;
  Linux)
    case "$arch" in
      x86_64 | amd64) file="mnema-linux-x86_64.tar.gz" ;;
      *)
        echo "mnema: no prebuilt binary for Linux/$arch yet" >&2
        echo "mnema: current prebuilts support universal macOS and Linux/x86_64" >&2
        exit 1
        ;;
    esac
    ;;
  *)
    echo "mnema: unsupported OS: $os" >&2
    exit 1
    ;;
esac

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

echo "Downloading $BASE/$file …"
curl -fsSL "$BASE/$file" -o "$tmp/$file"
curl -fsSL "$BASE/$file.sha256" -o "$tmp/$file.sha256"

expected="$(awk '{print $1}' "$tmp/$file.sha256")"
if command -v sha256sum >/dev/null 2>&1; then
  actual="$(sha256sum "$tmp/$file" | awk '{print $1}')"
else
  actual="$(shasum -a 256 "$tmp/$file" | awk '{print $1}')"
fi
if [ "$expected" != "$actual" ]; then
  echo "mnema: checksum mismatch (expected $expected, got $actual) — aborting" >&2
  exit 1
fi

tar -xzf "$tmp/$file" -C "$tmp"
mkdir -p "$DIR"
install -m 755 "$tmp/mnema" "$DIR/mnema"

echo
echo "Installed: $DIR/mnema  ($("$DIR/mnema" --help 2>&1 | head -n 1 || true))"
case ":$PATH:" in
  *":$DIR:"*) ;;
  *) echo "Note: $DIR is not on your PATH — add:  export PATH=\"$DIR:\$PATH\"" ;;
esac
echo
echo "Next steps:"
echo "  mnema serve                          # the shared local store (http://127.0.0.1:7077)"
echo "  claude mcp add mnema -- mnema mcp    # give Claude Code consult/learn/related/list"
echo "                                       # (mcp auto-starts the store — serve is optional)"
echo "  mnema consult \"what do we know…\"     # query from the shell"
echo
echo "Data lives in ~/.mnema. Docs: https://mnema.zimac.ai"
