#!/bin/sh
# LaPis memory MCP server (stdio).
#
# LaPis keeps one SQLite store, on arceus (~/.pi/memory/memory.db). Hosts that
# have the checkout run it directly; hosts that do not (the Deck) bridge stdio
# over ssh to the host that does. One wrapper, so every agent config can point
# at the same path regardless of machine.
set -eu

LAPIS="${LAPIS_DIR:-$HOME/.pi/agent/git/github.com/GeneGulanesJr/LaPis}"

node_bin() {
    if command -v node >/dev/null 2>&1; then
        command -v node
        return
    fi
    for candidate in "$HOME"/.local/share/mise/installs/node/*/bin/node; do
        [ -x "$candidate" ] && { printf %s "$candidate"; return; }
    done
    return 1
}

# One store, one host. The store lives on arceus; a host that merely has the
# checkout is a client. Without this, a fresh clone on a client host silently
# forks the memory: the wrapper would start writing to an empty local DB while
# every memory already made on arceus became invisible to that host.
#
# Set LAPIS_FORCE_REMOTE=1, or drop the remote's "user@host" into
# ~/.pi/memory/REMOTE_STORE, to force the bridge. Both are host-local: they
# never travel with dotfiles, so the host holding the store is unaffected.
FORCE_REMOTE=${LAPIS_FORCE_REMOTE:-0}
if [ -f "$HOME/.pi/memory/REMOTE_STORE" ]; then
    FORCE_REMOTE=1
    STORE_HOST=$(tr -d ' \n' < "$HOME/.pi/memory/REMOTE_STORE")
    [ -n "$STORE_HOST" ] && LAPIS_REMOTE="$STORE_HOST"
fi

if [ "$FORCE_REMOTE" != 1 ] && [ -f "$LAPIS/memory-store.js" ]; then
    NODE=$(node_bin) || { echo "mcp-lapis: no node found for the local LaPis store" >&2; exit 1; }
    exec "$NODE" "$LAPIS/memory-store.js" mcp
fi

if [ "$FORCE_REMOTE" = 1 ]; then
    echo "mcp-lapis: using the shared store on ${LAPIS_REMOTE:-ziadarafat@10.0.0.23}" >&2
fi

# No local store: bridge to the host that has one. LAPIS_REMOTE defaults to the
# personal homelab host; keep it a plain "user@host" so ProxyJump/ssh config apply.
REMOTE="${LAPIS_REMOTE:-ziadarafat@10.0.0.23}"
REMOTE_LAPIS="${LAPIS_REMOTE_DIR:-/home/ziadarafat/.pi/agent/git/github.com/GeneGulanesJr/LaPis}"

exec ssh -T -o BatchMode=yes -o ServerAliveInterval=30 "$REMOTE" \
    "/home/ziadarafat/.local/share/mise/installs/node/24.22.3/bin/node $REMOTE_LAPIS/memory-store.js mcp"
