#!/bin/bash

u=$(whoami)
if [ "x$u" != "xroot" ]; then
  sudo /bin/xlinux-security-dns "$1"
  exit $?
fi

dnsserver=$1

# EU-DNS-SERVER
DNS_OFF=""
DNS_M=" 86.54.11.201 86.54.11.1 "
DNS_MPA=" 86.54.11.211 86.54.11.11 "
DNS_MA=" 86.54.11.213 86.54.11.13 "
DNS_MP=" 86.54.11.212 86.54.11.12 "

# EU-DNS-SERVER
DNS_OFF=""
# Quad9 + EU
DNS_M=" 9.9.9.9 149.112.112.112 86.54.11.201 86.54.11.1 "
# adguard-dns.io + EU
DNS_MPA=" 94.140.14.15 94.140.15.16 86.54.11.211 86.54.11.11 "
DNS_MA=" 94.140.14.14 94.140.15.15 86.54.11.213 86.54.11.13 "

# EU-DNS-SERVER
DNS_MP=" 86.54.11.212 86.54.11.12 "


c=$(grep "^nameserver " /etc/resolv.conf | head -1 | awk '{print $2}')

CURRENT="OFF"
if [[  "$DNS_M" == *" $c "* ]]; then CURRENT="M"; fi
if [[ "$DNS_MP" == *" $c "*  ]]; then CURRENT="MP"; fi
if [[ "$DNS_MA" == *" $c "*  ]]; then CURRENT="MA"; fi
if [[ "$DNS_MPA" == *" $c "*  ]]; then CURRENT="MPA"; fi

#xlinux-settings set XLINUXSECURITY_DNS_CURRENT $CURRENT

E1=$(xlinux-settings get WARTUNGSSERVICE_AVAILABLE || echo 0)
E2=$(xlinux-settings get XLINUXSECURITY_DNS_SET || echo "OFF")

if [ "$E1" == "0" ]; then
  E2="OFF";
fi

if [ "$E2" != "$CURRENT" ]; then
  i="DNS_$E2"
  dnsserver=${!i}
  xlinux-settings set XLINUXSECURITY_DNS_CURRENT $E2
  nmcli -g name,type connection  show  --active | awk -F: '/ethernet|wireless/ { print $1 }' | while read connection
  do
    #nmcli con mod "$connection" ipv6.ignore-auto-dns yes
    #nmcli con mod "$connection" ipv4.ignore-auto-dns yes
    #echo $read $connection
    nmcli con mod "$connection" ipv4.dns " $dnsserver "
    if [ "x$dnsserver" == "x" ]; then
      nmcli con mod "$connection" ipv4.method auto
    fi
    #nmcli con down "$connection" && nmcli con up "$connection"
    #notify.send "DNS-Filter geändert"
  done
  service NetworkManager restart
fi
exit 0
