#!/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 "=== service-smoke: systemd service lifecycle test ==="

# 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
        echo "Service is active."
        break
    fi
    sleep 1
done

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

echo "--- Checking PID file ---"
if [ ! -f /run/activemq/main.pid ]; then
    echo "FAIL: PID file /run/activemq/main.pid not found"
    dump_diagnostics
    exit 1
fi
echo "PID file exists: $(cat /run/activemq/main.pid)"

echo "--- Waiting for port 61616 to be listening (broker ready) ---"
for i in $(seq 1 90); do
    if ss -ltn 2>/dev/null | grep -q ':61616'; then
        echo "Port 61616 is listening."
        break
    fi
    sleep 1
done

if ! ss -ltn 2>/dev/null | grep -q ':61616'; then
    echo "FAIL: port 61616 not listening after 90 seconds (broker did not reach ready state)"
    dump_diagnostics
    exit 1
fi

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

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

if systemctl is-active --quiet activemq@main; then
    echo "FAIL: activemq@main still running after stop"
    exit 1
fi

echo "--- Checking PID file is cleaned up ---"
if [ -f /run/activemq/main.pid ]; then
    echo "WARN: PID file still exists after stop (may be expected with forking type)"
fi

echo "=== service-smoke: PASS ==="
