#!/bin/sh
# Antonio Ávila for Fon Technology (GPL)
#


crontab_file="/etc/config/cron"
ntp_file="/etc/config/ntpservers"


config_ntpserver()
{
	verify="false"
	# If the hour of La Fonera is ok, then
	# the script exits
	if [ "`date +%Y`" != "2000" ]
	then
		return 0
	fi

	while [ "$verify" != "true" ]
	do
		#Kill them all!
		killall ntpclient > /dev/null 2>&1
		
		#Flush previous ntp servers...
		cat $crontab_file | grep -v ntp > $crontab_file
		randline=$(expr `head -c1 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % `wc -l $ntp_file | sed 's/^\ [ \t]*//' | cut -d" " -f1` + 1)	
		ntpserver=$(head -n$randline $ntp_file | tail -n1)	
	        randminute=$(expr `head -c2 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % 60)
	        randhour=$(expr `head -c2 /dev/urandom | hexdump -d | sed 's/\ //g' | sed 's/^0*//' | head -n1` % 24)
		
		# Testing if the host still  exists
		ping -c1 $ntpserver > /dev/null 2>&1
		
		if [ "$?" == "0" ]
		then
			# Ok, host seems to exists, trying to configure the date
		        ntpclient -s -h $ntpserver &
			
			# We wait 5 seconds to let the ntpserver configure if ater
			# this time the ntp is still running then the server is too
			# busy or is not working, so let's select another one.
			sleep 5
			ps aux > /tmp/psaux
			grep -q $ntpserver /tmp/psaux
			
			# If ntp is not running then everything should be ok!
			if [ "$?" != "0" ]
			then
				if [ "`date +%Y`" != "2000" ]
				then
					verify="true"
				fi
			fi
		fi
	done

        echo "$randminute $randhour * * * ntpclient -s -h $ntpserver" >> $crontab_file
        crontab -l

}
	
	case "$1" in
		"start")
			config_ntpserver&
			;;
		"stop")
			cat $crontab_file | grep -v "ntp" > $crontab_file
			crontab -l
			return
			;;
		*)
			echo "Usage: /etc/init.d/$NAME {start|stop}"
	                exit 1
			;;
	esac
	
