#!/bin/sh
#
# ntpd		This shell script takes care of starting and stopping
#		ntpd (NTPv4 daemon).
#
# chkconfig: - 58 74
# description: ntpd is the NTPv4 daemon.

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

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

if [ -f /etc/sysconfig/ntpd ];then
        . /etc/sysconfig/ntpd
fi

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

ntpconf=/etc/ntp.conf
ntpstep=/etc/ntp/step-tickers

[ -x /usr/sbin/ntpd -a -f $ntpconf ] || exit 0

RETVAL=0
prog="ntpd"

# Is there a firewall running, and does it look like one we configured?
FWACTIVE=
if iptables -L -n 2>/dev/null | grep -q RH-Lokkit-0-50-INPUT ; then
    FWACTIVE=1
fi

start() {
	tickers=''
	if [ -n "$FWACTIVE" -a "$FIREWALL_MODS" != "no" ]; then
	    echo -n $"$prog: Opening firewall for port 123"
	    iptables -I RH-Lokkit-0-50-INPUT -m udp -p udp -s 0/0  --sport 123 -d 0/0 --dport 123 -j ACCEPT\
		&& success || failure
	    echo
	fi
	if [ -s "$ntpstep" ]; then
                tickers=`/bin/sed -e 's/\#.*$//g' $ntpstep`
		echo -n $"$prog: Synchronizing with time server: "
		/usr/sbin/ntpdate -s -b -p 8 $tickers
		RETVAL=$?
		[ $RETVAL -eq 0 ] && success || failure
		echo
		[ ! $RETVAL -eq 0 ] && return $RETVAL
	else
		# -g can replace the grep for time servers
		# as it permits ntpd to violate its 1000s limit once.
		OPTIONS="$OPTIONS -g"
	fi
        # Start daemons.
        echo -n $"Starting $prog: "
        daemon ntpd $OPTIONS
	RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && touch /var/lock/subsys/ntpd
	return $RETVAL
}

stop() {
        # Stop daemons.
	if [ -n "$FWACTIVE" -a "$FIREWALL_MODS" != "no" ]; then
	    echo -n $"$prog: Removing firewall opening for port 123"
	    iptables -D RH-Lokkit-0-50-INPUT -m udp -p udp -s 0/0  --sport 123 -d 0/0 --dport 123 -j ACCEPT\
		&& success || failure
	    echo
	fi
        echo -n $"Shutting down $prog: "
	killproc ntpd
	RETVAL=$?
        echo
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/ntpd
	return $RETVAL
}

# See how we were called.
case "$1" in
  start)
	start
        ;;
  stop)
	stop
        ;;
  status)
	status ntpd
	RETVAL=$?
	;;
  restart|reload)
	stop
	start
	RETVAL=$?
	;;
  condrestart)
	if [ -f /var/lock/subsys/ntpd ]; then
	    stop
	    start
	    RETVAL=$?
	fi
	;;
  *)
        echo $"Usage: $0 {start|stop|restart|condrestart|status}"
        exit 1
esac

exit $RETVAL
