#!/bin/bash

set -e

case "$1" in
    purge)
        echo "Purging wild-central configuration..."

        # Remove polkit rules
        if [ -f /etc/polkit-1/rules.d/50-wild-central.rules ]; then
            rm -f /etc/polkit-1/rules.d/50-wild-central.rules
            echo "Removed polkit rules"
        fi

        # Remove sudoers file
        if [ -f /etc/sudoers.d/wild-central ]; then
            rm -f /etc/sudoers.d/wild-central
        fi

        # Remove dnsmasq configuration
        if [ -f /etc/dnsmasq.d/wild-cloud.conf ]; then
            rm -f /etc/dnsmasq.d/wild-cloud.conf
            echo "Removed dnsmasq configuration"
        fi

        # Remove systemd-resolved configuration
        if [ -f /etc/systemd/resolved.conf.d/wild-cloud.conf ]; then
            rm -f /etc/systemd/resolved.conf.d/wild-cloud.conf
            echo "Removed systemd-resolved configuration"
            systemctl restart systemd-resolved 2>/dev/null || true
        fi

        # Restore /etc/resolv.conf if we have a backup
        if [ -f /etc/resolv.conf.wild-backup ]; then
            echo "Restoring original /etc/resolv.conf from backup"
            rm -f /etc/resolv.conf
            mv /etc/resolv.conf.wild-backup /etc/resolv.conf
        fi

        # Remove configuration directory
        if [ -d /etc/wild-central ]; then
            rm -rf /etc/wild-central
        fi

        # Remove log directory
        if [ -d /var/log/wild-central ]; then
            rm -rf /var/log/wild-central
        fi

        # Remove lib directory
        if [ -d /var/lib/wild-central ]; then
            rm -rf /var/lib/wild-central
        fi

        # Remove nginx site
        if [ -L /etc/nginx/sites-enabled/wild-central ]; then
            rm -f /etc/nginx/sites-enabled/wild-central
            echo "Disabled wild-central nginx site"
        fi

        # Only remove wildcloud user if wild-cloud package is not installed
        if ! dpkg -s wild-cloud >/dev/null 2>&1; then
            if id wildcloud >/dev/null 2>&1; then
                userdel wildcloud || true
            fi
        fi

        echo "wild-central purged successfully"
        ;;

    remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
        ;;

    *)
        echo "postrm called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

exit 0
