#!/bin/bash

# --- CONFIGURATION ---
LOG_DIR="/home/"
LOG_FILE="$LOG_DIR/check_nameservers.log"
RESOLV_CONF="/etc/resolv.conf"
DRY_RUN=false # Set to false to actually perform changes

# Target IPv4 Resolvers
NEW_DNS_1="8.8.8.8"
NEW_DNS_2="1.1.1.1"
 

# 1. Grab nameserver lines
NAMESERVERS=$(grep '^nameserver' "$RESOLV_CONF" | awk '{print $2}')

# 2. Check if any IPv4 exists
HAS_IPV4=false
for ns in $NAMESERVERS; do
    if [[ $ns != *":"* ]]; then
        HAS_IPV4=true
        break
    fi
done

# 3. Action Phase
if [ "$HAS_IPV4" = false ]; then
    TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
    
    if [ "$DRY_RUN" = true ]; then
        echo "[$TIMESTAMP] DRY RUN: No IPv4 found. Would replace with $NEW_DNS_1 and $NEW_DNS_2"
    else
        # Log the change
        echo "[$TIMESTAMP] ALERT: Only IPv6 found. Overwriting $RESOLV_CONF" >> "$LOG_FILE"
        echo "[$TIMESTAMP] Old entries: $NAMESERVERS" >> "$LOG_FILE"

        # Backup current file
        cp "$RESOLV_CONF" "$RESOLV_CONF.bak-$(date +%F)"

        # Write new nameservers
        # We use a temp file to ensure an atomic write
        cat <<EOF > "$RESOLV_CONF.tmp"
; Manually set by check_nameservers script to prevent IPv6-only lockouts
nameserver $NEW_DNS_1
nameserver $NEW_DNS_2
EOF
        
        # Overwrite the original
        mv "$RESOLV_CONF.tmp" "$RESOLV_CONF"
        
        echo "[$TIMESTAMP] SUCCESS: Resolvers updated to $NEW_DNS_1 and $NEW_DNS_2" >> "$LOG_FILE"
        echo "DNS Updated. Check $LOG_FILE for details."
    fi
else
    if [ "$DRY_RUN" = true ]; then
        echo "IPv4 detected ($NAMESERVERS). No changes needed."
    fi
fi
