#!/bin/sh
# fix-liveconfig-shutdown-order.sh
#
# Workaround for: liveconfig.service can terminate with an uncaught SIGABRT
# during system shutdown/reboot if it is stopped concurrently with (or after)
# the local database server. LiveConfig's MySQL reconnect loop does not react
# to SIGTERM while sleeping in its exponential backoff, so if the DB service
# goes away first, LiveConfig can be killed mid-retry and log a crash/backtrace
# instead of stopping cleanly.
#
# Fix: add a systemd override to liveconfig.service that adds
# "After=<db.service>". systemd stops services in the REVERSE of their start
# order, so this makes systemd stop liveconfig.service BEFORE the database
# service on shutdown, preventing the race entirely. This does not touch
# LiveConfig's own package files and survives LiveConfig updates.
#
# Usage:
#   sudo ./fix-liveconfig-shutdown-order.sh
#
# Safe to re-run (idempotent).

set -e

if [ "$(id -u)" -ne 0 ]; then
    echo "Bitte als root ausfuehren (sudo $0)." >&2
    exit 1
fi

if ! systemctl list-unit-files liveconfig.service >/dev/null 2>&1; then
    echo "liveconfig.service wurde nicht gefunden - Abbruch." >&2
    exit 1
fi

# Detect which database service is actually in use on this box.
DB_SERVICE=""
for candidate in mariadb.service mysql.service mysqld.service; do
    if systemctl list-unit-files "$candidate" >/dev/null 2>&1; then
        DB_SERVICE="$candidate"
        break
    fi
done

if [ -z "$DB_SERVICE" ]; then
    echo "Kein bekannter Datenbank-Service (mariadb.service/mysql.service/mysqld.service) gefunden - Abbruch." >&2
    exit 1
fi

OVERRIDE_DIR="/etc/systemd/system/liveconfig.service.d"
OVERRIDE_FILE="$OVERRIDE_DIR/zz-shutdown-order-fix.conf"

echo "Gefundener Datenbank-Service: $DB_SERVICE"
mkdir -p "$OVERRIDE_DIR"

cat > "$OVERRIDE_FILE" << EOF
# Workaround: sorgt dafuer, dass systemd liveconfig.service beim Shutdown
# VOR ${DB_SERVICE} stoppt (systemd stoppt in umgekehrter Start-Reihenfolge).
# Verhindert, dass LiveConfigs MySQL-Reconnect-Loop waehrend eines
# gleichzeitigen DB-Stops in ein SIGABRT laeuft.
[Unit]
After=${DB_SERVICE}
EOF

systemctl daemon-reload

echo
echo "Override geschrieben nach: $OVERRIDE_FILE"
echo "Effektive After=-Abhaengigkeiten von liveconfig.service:"
systemctl show liveconfig.service -p After

echo
echo "Fertig. Kein Neustart von liveconfig.service noetig - die neue"
echo "Stop-Reihenfolge greift automatisch beim naechsten Shutdown/Reboot."
