#!/bin/bash
# spiral-demo.sh — 2-node envelope teleport demonstration.
#
# Launches two independent netspace servers on ports 9086 and 9087 with
# independent cache directories, runs the spiral client to drive one
# round-trip of envelope exchange in each direction, and tears down.
#
# Usage: bash examples/spiral-demo.sh [impl]
#   impl: python (default) | c | asm
#
# The implementation choice governs BOTH servers and the client.
# Any combination works at the protocol level; the script uses the
# same binary to keep the demo self-consistent.

set -e
ulimit -v 524288
trap 'pkill -9 -u "$USER" -f "proof-netspace-node|spiral-client" 2>/dev/null || true' EXIT INT TERM

IMPL="${1:-python}"

case "$IMPL" in
    python) BIN="python3 lumbda.py --fast" ;;
    c)      BIN="./c/lumbda --fast" ;;
    asm)    BIN="asm/lumbda" ;;
    *)      echo "unknown impl: $IMPL (expected python|c|asm)"; exit 1 ;;
esac

# Fresh state — no preloaded caches from prior runs
rm -rf /tmp/lumbda-A-db.sexp /tmp/lumbda-A-proofs
rm -rf /tmp/lumbda-B-db.sexp /tmp/lumbda-B-proofs
mkdir -p /tmp/lumbda-A-proofs /tmp/lumbda-B-proofs

echo "=== spiral demo ($IMPL) ==="

# Start both nodes
if [ "$IMPL" = "asm" ]; then
    timeout 25 $BIN < examples/proof-netspace-node-a.lsp > /tmp/spiral-a.log 2>&1 &
    SPID_A=$!
    timeout 25 $BIN < examples/proof-netspace-node-b.lsp > /tmp/spiral-b.log 2>&1 &
    SPID_B=$!
else
    timeout 25 $BIN examples/proof-netspace-node-a.lsp > /tmp/spiral-a.log 2>&1 &
    SPID_A=$!
    timeout 25 $BIN examples/proof-netspace-node-b.lsp > /tmp/spiral-b.log 2>&1 &
    SPID_B=$!
fi

sleep 3

# Run spiral client
if [ "$IMPL" = "asm" ]; then
    timeout 15 $BIN < examples/spiral-client.lsp
else
    timeout 15 $BIN examples/spiral-client.lsp
fi

# Tear down
kill -TERM $SPID_A $SPID_B 2>/dev/null || true
sleep 1
kill -9 $SPID_A $SPID_B 2>/dev/null || true
wait $SPID_A 2>/dev/null || true
wait $SPID_B 2>/dev/null || true

echo
echo "=== node A log ==="
head -1 /tmp/spiral-a.log
echo "=== node B log ==="
head -1 /tmp/spiral-b.log

# Verify no stragglers
if pgrep -u "$USER" -f 'proof-netspace-node|spiral-client' > /dev/null; then
    echo "STRAGGLER — check pgrep manually"
    exit 1
fi
echo "clean"
