#!/usr/bin/env bash
set -euo pipefail

DNS_SERVERS=("1.1.1.1" "8.8.8.8")

echo "[fix-dns] Poking DNS now... "

# --- 1. ensure tailscale is NOT managing DNS (non-destructive) ---
if command -v tailscale >/dev/null 2>&1; then
    if tailscale status >/dev/null 2>&1; then
        echo "[fix-dns] Ensuring tailscale DNS is disabled"
        tailscale up --accept-dns=false >/dev/null 2>&1 || true
    fi
fi

# --- 2. detect active *real* NetworkManager connection ---
ACTIVE_CONN=$(
    nmcli -t -f NAME,TYPE,DEVICE con show --active \
    | grep -Ev ':(tun|loopback):' \
    | head -n1 \
    | cut -d: -f1
)

if [[ -z "$ACTIVE_CONN" ]]; then
    echo "[fix-dns] No active NetworkManager connection found; exiting."
    exit 0
fi

echo "[fix-dns] Active connection: $ACTIVE_CONN"

# --- 3. check current DNS on that connection ---
CURRENT_DNS=$(nmcli -g ipv4.dns con show "$ACTIVE_CONN" || true)

NEEDS_UPDATE=true
for dns in "${DNS_SERVERS[@]}"; do
    if grep -q "$dns" <<<"$CURRENT_DNS"; then
        NEEDS_UPDATE=false
        break
    fi
done

if $NEEDS_UPDATE; then
    echo "[fix-dns] Updating DNS for $ACTIVE_CONN"
    nmcli con mod "$ACTIVE_CONN" ipv4.ignore-auto-dns yes
    nmcli con mod "$ACTIVE_CONN" ipv4.dns "${DNS_SERVERS[*]}"
    nmcli con up "$ACTIVE_CONN" >/dev/null 2>&1 || true
else
    echo "[fix-dns] DNS already correct; no change needed"
fi

# --- 4. flush resolver cache ---
resolvectl flush-caches >/dev/null 2>&1 || true

echo "[fix-dns] Done."

