#!/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 "=== instance-migration: test sysvinit→systemd instance migration ==="

# Simulate a pre-existing sysvinit-era install where the admin had enabled
# the "main" instance by symlinking it into instances-enabled/. The postinst
# migration loop (debian/activemq.postinst) sees such symlinks and enables
# the corresponding systemd unit; we mirror that enable step here.
echo "--- Creating instances-enabled/main symlink (simulating sysvinit install) ---"
ln -sf /etc/activemq/instances-available/main /etc/activemq/instances-enabled/main
echo "Symlink exists: $(ls -la /etc/activemq/instances-enabled/main)"

echo "--- Enabling activemq@main.service (mirrors postinst migration loop) ---"
systemctl enable activemq@main.service 2>&1

echo "--- Checking that systemd unit was enabled for the instance ---"
if systemctl is-enabled "activemq@main.service" >/dev/null 2>&1; then
    echo "activemq@main.service is enabled."
else
    echo "FAIL: activemq@main.service is not enabled"
    exit 1
fi

echo "--- Verifying the service can start ---"
systemctl start activemq@main

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 start"
    dump_diagnostics
    exit 1
fi

echo "--- Cleanup: stopping service ---"
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 "=== instance-migration: PASS ==="
