#!/bin/sh
#
# rdate		This shell script takes care of setting date from ntp server on startup
#
# chkconfig:	2345 16 89
# description:	set time with rdate
# processname:	rdate

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down rdate
		exit 1
	fi
else
	exit 0
fi

SET_TIME=no

# Get service config
if [ -f /etc/sysconfig/rdate ]; then
	. /etc/sysconfig/rdate
fi

# internal functions
set_time ()
{
	if [ $? -eq 0 -a -x /sbin/hwclock ] && is_yes "${SYNC_HWCLOCK}"; then
		# Set the system clock.
		ARC=0
		SRM=0
		UTC=0

		if [ -f /etc/sysconfig/clock ]; then
			. /etc/sysconfig/clock

			# convert old style clock config to new values
			if [ "${CLOCKMODE}" = "GMT" ]; then
				UTC=true
			elif [ "${CLOCKMODE}" = "ARC" ]; then
				ARC=true
			fi
		fi

		if grep "system serial" /proc/cpuinfo | grep -q MILO ; then
			ARC=true
		fi

		CLOCKFLAGS="--systohc"

		if is_yes "$UTC" ; then
			CLOCKFLAGS="$CLOCKFLAGS --utc"
		else
			CLOCKFLAGS="$CLOCKFLAGS --localtime"
		fi

		if is_yes "$ARC" ; then
			CLOCKFLAGS="$CLOCKFLAGS -A"
		fi

		if is_yes "$SRM" ; then
			CLOCKFLAGS="$CLOCKFLAGS -S"
		fi

		if is_yes "${BACKGROUND}"; then
			# be quiet when in background
			/sbin/hwclock $CLOCKFLAGS
		else
			run_cmd "Syncing hardware clock" /sbin/hwclock $CLOCKFLAGS
		fi
	fi
}


# See how we were called.
case "$1" in
  start|restart|reload|force-reload)
	# Check if we have to do anything:
	if is_yes "${SET_TIME}" && [ -n "${RDATE_SERVERS}" ]; then
		if is_yes "${BACKGROUND}"; then
			# synchronize in background for faster startups
			run_cmd "$(nls "Setting time from remote server (bg): %s" "${RDATE_SERVERS}")" /bin/true
			run_cmd "Syncing hardware clock (bg)" /bin/true
			{
				rdate -l -s ${RDATE_SERVERS} > /dev/null 2>&1
				set_time
			}&
		else
			# or else synchronize in foreground for precise timestamps
			run_cmd "$(nls "Setting time from remote server: %s" "${RDATE_SERVERS}")" rdate -l -s ${RDATE_SERVERS}
			set_time
		fi
	fi
	;;
  stop)
	# nothing to do
	;;
  status)
	if [ -n "${RDATE_SERVERS}" ]; then
		rdate -l ${RDATE_SERVERS}
		echo -n "Local time: "
		date
		echo -n "Local machine hardware clock: "
		clock --show
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|status}"
	exit 3
esac
