#!/bin/sh
# debian/postrm
# Cleanup for guest-agent package

set -e

SERVICE_NAME="guest-agent.service"
SERVICE_PATH="/etc/systemd/system/${SERVICE_NAME}"

# --------------------------------------
# Reload systemd and reset service state
# --------------------------------------
cleanup_systemd() {
    # Only try if systemd is running
    if [ -d /run/systemd/system ]; then
        echo "Reloading systemd configuration..."
        systemctl daemon-reload >/dev/null 2>&1 || echo "Warning: daemon-reload failed" >&2
        # Reset failed state if any
        systemctl reset-failed "${SERVICE_NAME}" >/dev/null 2>&1 || true
    fi
}

# --------------------------------------
# Purge configuration files
# --------------------------------------
handle_purge() {
    echo "Purging ${SERVICE_NAME} configuration..."
    if [ -f "${SERVICE_PATH}" ]; then
        rm -f "${SERVICE_PATH}" || echo "Warning: Failed to remove ${SERVICE_PATH}" >&2
    fi
    cleanup_systemd
}

# --------------------------------------
# Main logic based on $1 argument
# --------------------------------------
case "$1" in
    purge)
        handle_purge
        ;;
    remove|upgrade|disappear|failed-upgrade|abort-install|abort-upgrade)
        cleanup_systemd
        ;;
    *)
        echo "postrm called with unknown argument '$1'" >&2
        exit 1
        ;;
esac

# Debhelper placeholder
#DEBHELPER#

exit 0
