#!/bin/bash
# Setup shared memory: clawd/memory becomes single source of truth
# echo-core/memory becomes a symlink to clawd/memory

set -euo pipefail

ECHO_MEMORY="/home/moltbot/echo-core/memory"
CLAWD_MEMORY="/home/moltbot/clawd/memory"
BACKUP="/home/moltbot/echo-core/memory.bak"

echo "=== Shared Memory Setup ==="
echo ""

# 1. Safety checks
if [ -L "$ECHO_MEMORY" ]; then
    echo "ERROR: echo-core/memory is already a symlink!"
    exit 1
fi

if [ ! -d "$CLAWD_MEMORY" ]; then
    echo "ERROR: clawd/memory does not exist!"
    exit 1
fi

# 2. Move echo.sqlite to clawd (only file missing there)
if [ -f "$ECHO_MEMORY/echo.sqlite" ] && [ ! -f "$CLAWD_MEMORY/echo.sqlite" ]; then
    echo "Moving echo.sqlite to clawd/memory..."
    mv "$ECHO_MEMORY/echo.sqlite" "$CLAWD_MEMORY/echo.sqlite"
    echo "  Done."
else
    echo "echo.sqlite already in clawd or not in echo — skipping."
fi

# 3. Backup echo-core/memory
echo "Creating backup at $BACKUP..."
if [ -d "$BACKUP" ]; then
    echo "  Backup already exists, removing old one..."
    rm -rf "$BACKUP"
fi
mv "$ECHO_MEMORY" "$BACKUP"
echo "  Done."

# 4. Create symlink
echo "Creating symlink: $ECHO_MEMORY -> $CLAWD_MEMORY"
ln -s "$CLAWD_MEMORY" "$ECHO_MEMORY"
echo "  Done."

# 5. Verify
echo ""
echo "=== Verification ==="
ls -la "$ECHO_MEMORY"
echo ""
echo "Test file access:"
ls "$ECHO_MEMORY/kb/index.json" 2>/dev/null && echo "  kb/index.json: OK" || echo "  kb/index.json: FAIL"
ls "$ECHO_MEMORY/echo.sqlite" 2>/dev/null && echo "  echo.sqlite: OK" || echo "  echo.sqlite: FAIL"

echo ""
echo "SUCCESS! echo-core/memory now points to clawd/memory."
echo "Backup saved at: $BACKUP"
