#!/bin/bash

lock_dns_to_resolved() {
  for file in /etc/systemd/network/*.network; do
    [[ -f $file ]] || continue
    if ! grep -q "^\[DHCPv4\]" "$file"; then continue; fi

    if ! sed -n '/^\[DHCPv4\]/,/^\[/p' "$file" | grep -q "^UseDNS="; then
      sudo sed -i '/^\[DHCPv4\]/a UseDNS=no' "$file"
    fi

    if grep -q "^\[IPv6AcceptRA\]" "$file" && ! sed -n '/^\[IPv6AcceptRA\]/,/^\[/p' "$file" | grep -q "^UseDNS="; then
      sudo sed -i '/^\[IPv6AcceptRA\]/a UseDNS=no' "$file"
    fi
  done
}

unlock_dns_to_dhcp() {
  for file in /etc/systemd/network/*.network; do
    [[ -f $file ]] || continue
    sudo sed -i '/^\[DHCPv4\]/{n;/^UseDNS=no$/d}' "$file"
    sudo sed -i '/^\[IPv6AcceptRA\]/{n;/^UseDNS=no$/d}' "$file"
  done
}

if [[ -z $1 ]]; then
  dns=$(gum choose --height 6 --header "Select DNS provider" Cloudflare Google DHCP Custom)
else
  dns=$1
fi

case "$dns" in
Cloudflare)
  sudo tee /etc/systemd/resolved.conf >/dev/null <<'EOF'
[Resolve]
DNS=1.1.1.1#cloudflare-dns.com 1.0.0.1#cloudflare-dns.com
FallbackDNS=9.9.9.9 149.112.112.112
DNSOverTLS=opportunistic
EOF
  lock_dns_to_resolved
  ;;

Google)
  sudo tee /etc/systemd/resolved.conf >/dev/null <<'EOF'
[Resolve]
DNS=8.8.8.8#dns.google 8.8.4.4#dns.google
FallbackDNS=9.9.9.9 149.112.112.112
DNSOverTLS=opportunistic
EOF
  lock_dns_to_resolved
  ;;

DHCP)
  sudo tee /etc/systemd/resolved.conf >/dev/null <<'EOF'
[Resolve]
DNSOverTLS=no
EOF
  unlock_dns_to_dhcp
  ;;

Custom)
  echo "Enter your DNS servers (space-separated, e.g. '192.168.1.1 1.1.1.1'):"
  read -r dns_servers

  if [[ -z $dns_servers ]]; then
    echo "Error: No DNS servers provided."
    exit 1
  fi

  sudo tee /etc/systemd/resolved.conf >/dev/null <<EOF
[Resolve]
DNS=$dns_servers
FallbackDNS=9.9.9.9 149.112.112.112
EOF
  lock_dns_to_resolved
  ;;
esac

sudo systemctl restart systemd-networkd systemd-resolved
