#!/bin/sh
#i'm sure somebody's already written this, but i couldn't find it, so
#i slapped this together.  stick it in cron.  it should work on any platform 
#with mods for local date-setting format.
#tim conway (hiram@indy.net)

#this thing should be able to synchronize you within a second or so behind utc
#per WWV. i've listed all seven addresses given by nist... that's overkill
#trim it down to a couple
#
#we check for a correction factor (delay compensation - if not found, will 
#output settinglines so cron can mail them to root to determine good delay 
#factor - use 0 to shut this thing up and accept small delays
delay=$1

#time-a.timefreq.bldrdoc.gov (132.163.135.130)
#time-b.timefreq.bldrdoc.gov (132.163.135.131)
#time-a.nist.gov (129.6.16.35)
#time-b.nist.gov (129.6.16.36)
#time.nist.gov (192.43.244.18)
#time-nw.nist.gov (131.107.1.10)
#utcnist.colorado.edu (128.138.140.44)

for server in 132.163.135.130 132.163.135.131 129.6.16.35 129.6.16.36 192.43.244.18 131.107.1.10 128.138.140.44
do
telnet $server 13 2>/dev/null
done |
grep UTC |
while read n1 date time n2 n3 n4 n4 tzind end
do
year=`echo $date |cut -d- -f1`
month=`echo $date |cut -d- -f2`
day=`echo $date |cut -d- -f3`
hour=`echo $time |cut -d: -f1`
minute=`echo $time |cut -d: -f2`
second=`echo $time |cut -d: -f3`

#here, we deal with time delay - nist doesn't have timeloss provisions on the
#internet side, so run it a few times, get the feel for how long it takes 
#(good bet - 1/2 the average time between lines, rounded up to the next second)
if [ "$delay" ]
then
second=`expr $second + $delay`
	if [ "$second" -gt 59 ]
	then
	second=`expr $second - 60`
	minute=`expr $minute + 1`
		if [ "$minute" -eq 60 ]
		then
		minute=0
		hour=`expr $hour + 1`
			if [ "$hour" -eq 24 ]
			then 
			hour=0
			day=`expr $day + 1`
			fi
		fi
	fi
fi
#don't run this at 1 til midnight on the last day of the month

#here's an ugly y2k kludge
if [ "$year" -lt 98 ]
then
century=20
else
century=19
fi

#here you have to make the local clock-setting string -this works for slakware
#linux - if you don't have the -u switch (set or display in utc), work it out.

setstring="$month$day$hour$minute$century$year.$second"

#echo $setstring
if [ "$delay" ]
then
date -u $setstring >/dev/null
else
date -u $setstring
fi

done
