#!/bin/sh
#author:Wos
#dns server change
function usage()
{
      echo "need root priority"
      echo "usage:`basename $0` [best isp dns server]"
      echo "     :`basename $0` <ip>[manual dns server ip]"
      echo "     :`basename $0` -s [dnscrypt dns server]"
      exit -1
}

#test root priority
[ `id -u` != 0 ] && usage

function unblockresolv()
{
    chattr -i /etc/resolv.conf
    chmod 777 /etc/resolv.conf
}


function blockresolv()
{
    chmod 444 /etc/resolv.conf
    chattr +i /etc/resolv.conf
}


if [ $# == 0 ]; then
    if [ ! -e /usr/local/sbin/fping ] && [ ! -e /usr/bin/fping ]; then
        echo "please install fping first(recommend 5.0 version)"
        echo "https://www.fping.org/dist/"
        exit -1
    fi
    while :;
    do
    LOC=$(curl --doh-url https://ns1.qquack.org/dns-query -s "https://ipinfo.io/country")
    if [[ "${LOC}" != "" ]]; then
        break
    fi
    done
    dnsip=$(curl --doh-url https://ns1.qquack.org/dns-query -s "https://public-dns.info/nameserver/${LOC,,}.txt"|shuf|head -50|grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}"|xargs -P8 -I % sh -c 'fping -c1 -t180 %'|grep bytes|awk '{print $1,$6}'|sort -k2 -g|uniq|awk '{print $1}'|head -1)
    unblockresolv
    echo "nameserver $dnsip" > /etc/resolv.conf
    clear
    echo "best isp domain server already set!"
    blockresolv
    exit -1
elif [ $# == 1 ]; then
    if [[ "$1" == "-s" ]]; then
        unblockresolv
        echo "nameserver 127.0.0.1" > /etc/resolv.conf
	echo "dnscrypt proxy server already set!"
        blockresolv
	exit -1
    fi
    dnsip=`echo $1|grep -x -E "([0-9]{1,3}\.){3}[0-9]{1,3}"`
    if [ $? == 0 ]; then
      unblockresolv
      echo "nameserver $dnsip" > /etc/resolv.conf
      clear
      echo "manual domain server already set!"
      blockresolv
      exit -1
    else
      usage
    fi

else
    usage
fi