#!/bin/sh
# Set DNS to 127.0.0.1 for all active network interfaces

# Get all active network interfaces
INTERFACES=$(networksetup -listallnetworkservices | grep -v "^\*" | tail -n +2)

cnt=0
while IFS= read -r iface; do
    # Get current DNS
    CURRENT_DNS=$(networksetup -getdnsservers "$iface" 2>/dev/null)
    
    # Skip if already set to 127.0.0.1
    if echo "$CURRENT_DNS" | grep -q "^127.0.0.1$"; then
        continue
    fi
    
    # Set DNS to 127.0.0.1
    networksetup -setdnsservers "$iface" 127.0.0.1 ::1
    cnt=$((cnt + 1))
done <<< "$INTERFACES"

# Flush DNS cache if any interface was changed
if [ $cnt -gt 0 ]; then
    dscacheutil -flushcache
    killall -HUP mDNSResponder
fi