#!/bin/bash

# Configuration
SOURCE_URL="https://webtools.tomdings.com/NsLookup/WebApi/getDatas.php"
RESOLV_CONF="/etc/resolv.conf"
BACKUP="/etc/resolv.conf.bak"

# Fetch list (assumed to be plain IPs, one per line)
dns_ips=$(curl -s "$SOURCE_URL" | head -n 4)

# Validate IPs (simple IPv4 format check)
valid_dns=$(echo "$dns_ips" | grep -Eo '^([0-9]{1,3}\.){3}[0-9]{1,3}$')

if [[ -z "$valid_dns" ]]; then
  echo "No valid DNS IPs found. Exiting."
  exit 1
fi

# Backup old resolv.conf
if [ ! -f "$BACKUP" ]; then
  cp "$RESOLV_CONF" "$BACKUP"
fi

# Optional: Disable systemd-resolved if it's controlling resolv.conf
if systemctl is-active --quiet systemd-resolved; then
  echo "Disabling systemd-resolved to take control of resolv.conf"
  systemctl disable --now systemd-resolved
  rm -f /etc/resolv.conf
  touch /etc/resolv.conf
fi

# Write new DNS servers to resolv.conf
{
  echo "# Generated on $(date)"
  for ip in $valid_dns; do
    echo "nameserver $ip"
  done
} > "$RESOLV_CONF"

echo "Updated $RESOLV_CONF with the top 4 fastest DNS servers:"
echo "$valid_dns"
