#!/bin/bash

maxlevel=3
filters="Moscow Russia"
NTPpools="ru.pool.ntp.org pool.ntp.org 0.debian.pool.ntp.org 1.debian.pool.ntp.org 2.debian.pool.ntp.org 3.debian.pool.ntp.org"

# Выделяем набор уникальных IP-адресов допустимых NTP-серверов пула
echo "Step #1..."
:> /tmp/NTPS.list
for server in $NTPpools
do
    for try in 1 2 3 4
    do
	nslookup "$server" 2>&1 | sed -e '1,/answer/d' | \
		grep -E ^Address: | cut -f2 -d ' ' >> /tmp/NTPS.list
    done
done
cat /tmp/NTPS.list | sort -u
echo ""

# Из полученного набора выделяем лишь те, которые пингуются, и сортируем их по доступности
echo "Step #2..."
:> /tmp/NTPT.list
cat /tmp/NTPS.list | sort -u | \
while read server
do
    echo -n "Checking $server..."
    if ping -c1 "$server" &>/dev/null
    then
	ping -c4 "$server" 2>&1 | \
	    grep '4 packets transmitted, 4 received, 0% packet loss, time' | \
		cut -f10 -d ' ' | sed "s/ms/:$server/" >> /tmp/NTPT.list
    fi
    echo -ne "                     \r"
done
cat /tmp/NTPT.list | sort -n
echo "                                       "

# Опрашиваем каждый сервер, одновременно тестируя доступность, определяя уровень и отбрасывая совершенно неподходящие
echo "Step #3..."
/usr/sbin/ntpdate -q `cat /tmp/NTPT.list | sort -n | cut -f2 -d:` 2>&1 | \
	grep -e ^server | sed 's/,//g' | awk '{print $8 " " $4 " " $2;}' | \
	sort -n > /tmp/NTPS.list
stratum=1
while [ $stratum -le $maxlevel ]
do
    header=0
    cat /tmp/NTPS.list | \
    while read delay level server
    do
	[ "$level" != "$stratum" ] && continue
	filter=""
	for search in $filters
	do
	    dummy=`whois "$server" 2>&1 | grep "$search"`
	    if [ -n "$dummy" ] ; then
		filter="$search"
		break
	    fi
	done
	if [ "$header" = "0" ] ; then
	    header=1
	    echo ""
	    echo "# Stratum ${stratum}:"
	fi
	if [ -n "$filter" ] ; then
	    echo "server ${server}	# Delay: ${delay}, Region: ${filter}"
	else
	    echo "server ${server}	# Delay: ${delay}"
	fi
    done
    stratum=`expr $stratum \+ 1`
done

rm -f /tmp/NTPS.list
rm -f /tmp/NTPT.list

