#! /bin/sh
# Copyright (c) 1995-2003 SuSE Linux AG, Nuernberg, Germany.
# All rights reserved.
#
# Author: Michael Andres
#
# /etc/init.d/ntp
#   and its symbolic link
# /usr/sbin/rcntp
#
### BEGIN INIT INFO
# Provides:       ntp ntpd xntpd 
# Required-Start: $remote_fs $syslog $named
# Required-Stop:  $remote_fs $syslog
# Default-Start:  2 3 5
# Default-Stop:   0 1 6
# Description:    Start network time protocol daemon (NTPD).
### END INIT INFO

# First reset status of this service
. /etc/rc.status
rc_reset

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running

# set default options
NTP_CONF="/etc/ntp.conf"
if [ ! -f ${NTP_CONF} ]; then
	echo -n "Time server configuration file, ${NTP_CONF} does not exist."
	# Tell the user this has skipped
	rc_status -s
	exit 6
fi

NTPD_INITIAL_NTPDATE="AUTO-2"
NTPD_OPTIONS="-u ntp"
NTPD_RUN_CHROOTED="yes"
NTPD_START="yes"

NTPD_BIN="/usr/sbin/ntpd"
if [ ! -x ${NTPD_BIN} ]; then
        echo -n "Time server, ${NTPD_BIN} not installed!"
        rc_status -s
        exit 5
fi

NTPDATE_BIN="/usr/sbin/ntpdate"

# Override defaults, if we have the sysconfig file
test -f /etc/sysconfig/ntp && . /etc/sysconfig/ntp

test "${NTPD_RUN_CHROOTED}" = "yes" && \
	CHROOT_PREFIX="/var/lib/ntp" || \
	CHROOT_PREFIX=""

NTPD_PID="${CHROOT_PREFIX}/var/run/ntp/ntpd.pid"
NTPD_PID_NOPREFIX="/var/run/ntp/ntpd.pid"

function ntpd_is_running() {	
    $0 status >/dev/null
}

function initial_ntpdate () {
    case "$NTPD_INITIAL_NTPDATE" in
    auto|Auto|AUTO)
    	MAX_AUTO=-1;
    	;;
    auto-*|Auto-*|AUTO-*)
    	MAX_AUTO=${NTPD_INITIAL_NTPDATE#*-};
    	;;
    *)
    	echo $NTPD_INITIAL_NTPDATE
    	return 0
    	;;
    esac
    # AUTO: Try to get server from config file
    if [ -r $NTP_CONF ] ; then
        cat $NTP_CONF | awk -v MAX_AUTO=$MAX_AUTO '
	    /^[[:space:]]*server[[:space:]]+127.127/ {
	    	next
	    }
	    /^[[:space:]]*(server|peer)[[:space:]]/ {
	    	if ( MAX_AUTO ) {
		    printf " %s", $2
		    if ( --MAX_AUTO == 0 )
		    	exit 0
		}
	    }
    	'
    fi

}

function set_cmos_clock () {
	if [ "$NTPD_ADJUST_CMOS_CLOCK" == yes ]; then
		echo -n "Try to set the CMOS clock"
		hwclock --systohc && echo $rc_done || echo $rc_failed
	fi
}

function parse_symlink
{
	if [ -c "$NTP_PARSE_DEVICE" ]; then
		if [ -n "$NTP_PARSE_LINK" ]; then
		ln -sf $NTP_PARSE_DEVICE $NTP_PARSE_LINK
		fi
	fi
}

function prepare_chroot
{
	for configfile in /etc/{localtime,ntp.conf} $NTPD_CHROOT_FILES; do
		test -d ${CHROOT_PREFIX}/${configfile%/*} || mkdir -p ${CHROOT_PREFIX}/${configfile%/*}
		cp -auL ${configfile} ${CHROOT_PREFIX}/${configfile%/*}
	done
	NTPD_OPTIONS="${NTPD_OPTIONS} -i ${CHROOT_PREFIX}"
}

case "$1" in
    start)
	# get the initial date from the timeservers configured in ntp.conf
	NTPDATE_FROM=$(initial_ntpdate)
	if [ -n "$NTPDATE_FROM" -a -x $NTPDATE_BIN ]; then
		ntpd_is_running || {
			echo -n "Try to get initial date and time via NTP from $NTPDATE_FROM"
			# -b: Set time on runlevel change, otherwise let
			#     ntpdate decide whether to slew or step.
			test -z $INIT_VERSION \
				&& FORCE_STEP="" \
				|| FORCE_STEP="-b"
			# -u: Use an unprivileged port for outgoing packets,
			#     may be we have to synchronise with hosts beyond
			#     a firewall.
			$NTPDATE_BIN -s $FORCE_STEP $NTPDATE_FROM \
				&& echo $rc_done \
				|| echo $rc_failed
			# error here is reported but not propagated.
		}
	fi
	# do we want to set the CMOS clock?
        set_cmos_clock

	if( ( test $NTPD_START = "yes" ) || ( test $NTPD_START = "Yes" ) || ( test $NTPD_START = "YES" ) )
	then
		echo -n "Starting network time protocol daemon (NTPD)"
		    # do we need a refclock symlink?
		parse_symlink
		# do we run chrooted?
		test "${NTPD_RUN_CHROOTED}" = "yes" && prepare_chroot
		# do we get the option iburst? 
		if [ -z $2 ]; then
		    	true
		else
		case $2 in
		        iburst)
			awk '{gsub ("^server.*","& iburst"); print $0}' /etc/ntp.conf > /var/lib/ntp/etc/ntp.conf.iburst
			export NTPD_OPTIONS="$NTPD_OPTIONS -c /var/lib/ntp/etc/ntp.conf.iburst"
		        ;;
		    	*)           echo "Unknown option $2"
		        echo "options: {iburst}"
			exit 1 ;;
		esac
		fi
		startproc $NTPD_BIN -p ${NTPD_PID_NOPREFIX} $NTPD_OPTIONS
	else
		echo -n "Do not start network time protocol daemon (NTPD) sysonfig varible set"
	fi
	rc_status -v
	;;
    stop)
	echo -n "Shutting down network time protocol daemon (NTPD)"
	killproc -p ${NTPD_PID} -TERM $NTPD_BIN
	rc_status -v
	rm -f ${NTPD_PID}
	;;
    try-restart)
        $0 status
        if test $? = 0; then
                $0 restart
        else
                rc_reset        # Not running is not a failure.
        fi
        # Remember status and be quiet
        rc_status
	;;
    restart)
	$0 stop
	$0 start
	rc_status
        ;;
    try-restart-iburst)
	$0 status
	if test $? = 0; then
                $0 stop
		$0 start iburst 
        else
                rc_reset        # Not running is not a failure.
        fi
	# Remember status and be quiet
	rc_status
        ;;
    force-reload)
	# Does not support signalling to reload
        $0 try-restart
	rc_status
	;;
    reload)
	echo -n "Reload network time protocol daemon (NTPD)"
	# Does not support signalling to reload
	rc_failed 3
	rc_status -v
	;;
    status)
	echo -n "Checking for network time protocol daemon (NTPD): "
	checkproc -p ${NTPD_PID} $NTPD_BIN
	rc_status -v
	;;
    probe)
	# test /etc/ntp.conf -nt /var/run/ntp.pid && echo restart
	rc_failed 3
	;;
    ntptimeset)
	NTPDATE_FROM=$(initial_ntpdate)
	if [ -n "$NTPDATE_FROM" -a -x $NTPDATE_BIN ]; then
		if ntpd_is_running; then
			echo -n "Can't set time while ntpd is running"
			rc_failed 2
			rc_status -v
		else
			echo -n "Try to get initial date and time via NTP from $NTPDATE_FROM"
			# -b: Set time on runlevel change, otherwise let 
			#     ntpdate decide whether to slew or step.
			test -z $INIT_VERSION \
				&& FORCE_STEP="" \
				|| FORCE_STEP="-b"
			# -u: Use an unprivileged port for outgoing packets,
			#     may be we have to synchronise with hosts beyond 
			#     a firewall.
			$NTPDATE_BIN -s $FORCE_STEP $NTPDATE_FROM \
				&& echo $rc_done \
				|| echo $rc_failed
			# error here is reported but not propagated.
		fi
	fi
	;;
    *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|try-restart-iburst|force-reload|reload|probe|ntptimeset}"
	exit 1
	;;
esac
rc_exit
