#!/bin/sh
set -e

echo "Running generate-ui.sh..."
bash /usr/share/prometheus/alertmanager/generate-ui.sh

echo "Verifying generated files exist..."
DSTDIR=/usr/share/prometheus/alertmanager/ui
if [ ! -s "$DSTDIR/script.js" ]; then
    echo "ERROR: script.js is missing or empty!"
    exit 1
fi
if [ ! -s "$DSTDIR/index.html" ]; then
    echo "ERROR: index.html is missing or empty!"
    exit 1
fi
if [ ! -s "$DSTDIR/favicon.ico" ]; then
    echo "ERROR: favicon.ico is missing or empty!"
    exit 1
fi

echo "Restarting prometheus-alertmanager..."
systemctl restart prometheus-alertmanager
systemctl is-active prometheus-alertmanager

echo "Waiting for service to listen on 9093..."
for i in $(seq 1 10); do
    if curl -s http://localhost:9093/-/ready > /dev/null; then
        echo "Alertmanager is ready!"
        break
    fi
    echo "Waiting for Alertmanager..."
    sleep 1
done

echo "Verifying UI is served..."
# Alertmanager serves the UI on / (or /#/alerts). We verify that script.js is reachable.
if ! curl -s -f http://localhost:9093/script.js > /dev/null; then
    echo "ERROR: Failed to fetch script.js via HTTP!"
    exit 1
fi

if ! curl -s -f http://localhost:9093/ > /dev/null; then
    echo "ERROR: Failed to fetch index.html via HTTP!"
    exit 1
fi

echo "Autopkgtest generate-ui completed successfully."
