#!/bin/bash
# Start the bundled STOMP broker (tools/stomp_broker.py) on port 61613
# for the phpt suite; teardown stops it.
set -e
BASEDIR=$(dirname "$(dirname "$(readlink -f "$0")")")
TOOLSDIR="$BASEDIR/tools"

PY=$(command -v python3 || command -v python || true)
if [ -z "$PY" ]; then
    echo "ERROR: no python3 or python to run the STOMP broker" >&2
    exit 1
fi

# fd 3 is closed so a bats caller does not wait for the broker to exit
"$PY" "$TOOLSDIR/stomp_broker.py" 61613 \
    >"$TOOLSDIR/stomp_broker.log" 2>&1 </dev/null 3>&- &
echo $! > "$TOOLSDIR/stomp_broker.pid"

READY=0
for attempt in $(seq 1 20); do
    if "$PY" -c "import socket; s=socket.socket(); s.settimeout(0.5); s.connect(('127.0.0.1', 61613)); s.close()" 2>/dev/null; then
        READY=1
        break
    fi
    sleep 0.25
done

if [ "$READY" -ne 1 ]; then
    echo "ERROR: STOMP broker failed to start after 20 attempts" >&2
    cat "$TOOLSDIR/stomp_broker.log" >&2 || true
    exit 1
fi
