#!/bin/sh

# |Rain|'s time syncing script v1.3

# Set the below to 1 if you want to have output written to syslog
USE_SYSLOG="1"
# Time server to use
SERVER="blackhole"
# Program to write time to CMOS (hwclock needs -u for GMT)
CLOCKUPDATE="hwclock -w -u"

# Run with -w to         auto-write to cmos (for a crontab)
# Run with -n to disable auto-write to cmos (for a crontab)

# You can use this crontab to sync every 15 minutes, results mailed to you.
# */15 * * * * synctime
# You can use this crontab to sync every 15 minutes, errors mailed to you.
# */15 * * * * synctime > /dev/null
# You can use this crontab to sync every 15 minutes, nothing mailed to you.
# */15 * * * * synctime > /dev/null 2 > /dev/null

if [ "$USER" != "root" ]; then
	if [ "$USER" != "" ]; then
		echo "You must be root (uid 0) to run this program." >&2
		echo "You are currently $USER@`hostname`" >&2
		exit
	fi
fi

PATH="$PATH:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin"

if [ "$*" = "-w" ]; then
	save="y"
elif [ "$*" = "-n" ]; then
	save="n"
elif [ "$*" != "" ]; then
	echo "|Rain|'s time syncing script." >&2
	echo "Usage:" >&2
	echo "    Interactive              : $0" >&2
	echo "Non-Interactive w/CMOS write : $0 -w" >&2
	echo "Non-Interactive wo/CMOS write: $0 -n" >&2
	exit
fi

BEFORE="`date \"+Current Time   :                                    %a %b %e %H:%M:%S.000\"`"
date "+Current Time   :                                    %a %b %e %H:%M:%S.000"
echo -n "Network Time   : "
NETDATE="`netdate $SERVER`"
ERR="$?"
echo $NETDATE
AFTER="`date \"+New Time       :                                    %a %b %e %H:%M:%S.000\"`"
date "+New Time       :                                    %a %b %e %H:%M:%S.000"
if [ -z "$save" ]; then
	echo -n "CMOS write (yN): "
	read save
fi
if [ "$save" = "y" ]; then
	echo -n "CMOS write     : "
	$CLOCKUPDATE
	echo Done
else
	echo "CMOS write     : skipped"
fi
if [ ! -z "$USE_SYSLOG" ]; then
	if [ "$ERR" != "0" ]; then
		logger -t "synctime" "Sync Error!"
		exit
	fi
	if [ "$save" = "y" ]; then
		written="(written to CMOS)"
	else
		written=""
	fi
	logger -t "synctime" "`cut -d\  -f46 << .
$BEFORE
.` `cut -d\  -f2 << .
$NETDATE
.` $written"
fi
