#!/bin/bash

export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

LOG="/var/log/SafeDNS_uninstall.log"

# Write log entries
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') — $*" | sudo tee -a "$LOG" >/dev/null
}

# Auto-detect SafeDNS app path
APP_PATH=$(find /Applications -type d -name "SafeDNS Agent.app" -maxdepth 1 2>/dev/null | head -n 1)
CONFIG="/etc/agentsafedns/settings.conf"

log "🔧 Terminating SafeDNS processes..."
sudo killall -9 AgentSafeDns 2>/dev/null
sudo killall -9 AgentSafeDnsGui 2>/dev/null

if [ -n "$APP_PATH" ] && [ -d "$APP_PATH" ]; then
    log "🧹 Removing application: $APP_PATH"
    sudo rm -rf "$APP_PATH"
else
    log "⏩ Skipping removal: application not found."
fi

if [ -f "$CONFIG" ]; then
    log "🧽 Removing configuration file: $CONFIG"
    sudo rm "$CONFIG"
else
    log "⏩ Configuration already removed or not found."
fi

log "🔄 Resetting DNS settings..."

# Filter out internal or unsupported services
INTERFACES=$(networksetup -listallnetworkservices | tail +2 | grep -vE '^\*|USB|LAN|Bridge|Thunderbolt|iPhone|10/100')

for SERVICE in $INTERFACES; do
    if networksetup -getdnsservers "$SERVICE" >/dev/null 2>&1; then
        log "🔁 Resetting DNS for: $SERVICE"
        sudo networksetup -setdnsservers "$SERVICE" "Empty"
    else
        log "⚠️ Skipping: $SERVICE does not support DNS configuration"
    fi
done

log "✅ Removal complete."
