#!/bin/sh

set -eu

AMQ_LOG=/var/lib/activemq/main/data/activemq.log

dump_diagnostics() {
    echo "--- journalctl ---"
    journalctl -u activemq@main --no-pager
    if [ -f "$AMQ_LOG" ]; then
        echo "--- $AMQ_LOG (last 100 lines) ---"
        tail -n 100 "$AMQ_LOG"
    else
        echo "--- $AMQ_LOG not found ---"
    fi
}

echo "=== broker-connectivity: test broker accepts TCP connections ==="

# Enable the default "main" instance
ln -sf /etc/activemq/instances-available/main /etc/activemq/instances-enabled/main

echo "--- Starting activemq@main ---"
systemctl start activemq@main

echo "--- Waiting for service to become active ---"
for i in $(seq 1 90); do
    if systemctl is-active --quiet activemq@main; then
        break
    fi
    sleep 1
done

if ! systemctl is-active --quiet activemq@main; then
    echo "FAIL: activemq@main did not start"
    dump_diagnostics
    exit 1
fi

echo "--- Waiting for port 61616 to be listening ---"
for i in $(seq 1 90); do
    if nc -z 127.0.0.1 61616 2>/dev/null; then
        echo "Port 61616 is open."
        break
    fi
    sleep 1
done

if ! nc -z 127.0.0.1 61616 2>/dev/null; then
    echo "FAIL: port 61616 not listening after 90 seconds"
    dump_diagnostics
    exit 1
fi

echo "--- Checking OpenWire handshake ---"
# ActiveMQ sends a WireFormatInfo packet on new connections
HANDSHAKE=$(echo "" | nc -w 2 127.0.0.1 61616 2>/dev/null | head -c 20 | xxd -p)
if echo "$HANDSHAKE" | grep -q "^000000"; then
    echo "Received OpenWire wire format header (starts with length prefix)."
else
    echo "WARN: Unexpected handshake bytes: $HANDSHAKE"
fi

echo "--- Stopping activemq@main ---"
systemctl stop activemq@main

for i in $(seq 1 90); do
    if ! systemctl is-active --quiet activemq@main; then
        break
    fi
    sleep 1
done

echo "=== broker-connectivity: PASS ==="
