#!/bin/sh

. /etc/init.d/LIB
clock=`pathof clock /sbin:/etc:/usr/sbin:/usr/etc:/bin:/usr/bin`
adjtimex=`pathof adjtimex /sbin:/etc/:/usr/sbin:/usr/etc:/bin:/usr/bin`


# Extract info from /etc/default/clock.
set -- `awk '
	BEGIN			{ HWCLOCK="X"; GAINPERDAY="X" }
	/^[ \t]*HWCLOCK/	{ HWCLOCK=$2 }
	/^[ \t]*GAINPERDAY/	{ GAINPERDAY=$2 }
	END			{ print HWCLOCK, GAINPERDAY }
' /etc/default/clock`
HWCLOCK=$1
GAINPERDAY=$2

# If we have adjtimex and a seconds gain per day defined we use it to
# adjust the kernel tick frequency.
if [ -n "$adjtimex" -a "$GAINPERDAY" != "X" ]; then
	# Round down to a multiple of 5 seconds. Below 5 seconds the
	# change in tick value is fractional.
	secs=`expr $GAINPERDAY / 5 '*' 5 2> /dev/null`

	# Convert to a tick value. Yeah, we could do it in one...
	secs=`expr 864000000 / \( 86400 + $secs \)`

	if [ -n "$secs" -a "$secs" != "0" ]; then
		$adjtimex -tick $secs
	fi
fi

# If we can see clock out there use it to set the date/time from
# the hardware clock. If we have an /etc/adjtime we use the -a
# argument to clock rather than -s in order to correct for hardware
# clock drift. See the manual page for clock for details of how to
# set this up. (Older versions of clock may not have this feature).
if [ -n "$clock" ]; then
	if [ -f /etc/adjtime ]; then
		clockarg=-a
	else
		clockarg=-s
	fi

	case "$HWCLOCK" in
		GMT|UTC|UCT|UT|CUT|Z|ZULU)
			$clock -u $clockarg
			;;
		*)
			$clock $clockarg
			;;
	esac
fi
