#!/bin/bash
#
# ntpd         This shell script takes care of starting and stopping
#              ntpd (NTPv4 daemon).
#
# chkconfig: 2345 56 10
# description: ntpd is the NTPv4 daemon.

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

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

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

[ -x /usr/sbin/ntpd -a -f /etc/ntp.conf ] || exit 0

RETVAL=0

# See how we were called.
case "$1" in
  start)
  	# are we already running?
	# otherwise there could be multiple ntpd copies running
	# yes, ntpd will start even if it cannot bind to its port
	if [ -f /var/lock/subsys/ntpd -a -n "`pidof ntpd`" ]; then
		action "Starting ntpd: " /bin/false
		gprintf "ntpd subsystem locked (and there are ntpd processes running)\n"
		exit 1
	fi
	# Adjust time to make life easy for ntpd
	if [ -s /etc/ntp/step-tickers ]; then
		/usr/sbin/ntpdate -s -b -p 8 -u `cat /etc/ntp/step-tickers`
		RETVAL=$?
		gprintf "Syncing time for ntpd: "
		if [ "$RETVAL" = "0" ]; then
			success
		else
			failure
		fi
		echo
	fi
        # Start daemons.
        gprintf "Starting ntpd: "
	# if capability is a module, we have to load it
	if [ -f "/lib/modules/`uname -r`/kernel/security/capability.ko" ]; then
		if ! grep -q "^capability " /proc/modules; then
			modprobe capability
		fi
	fi	
	daemon ntpd -A -u ntp:ntp
	RETVAL=$?
        echo
	if [ "$RETVAL" = "0" ]; then
	       touch /var/lock/subsys/ntpd
	fi
        ;;
  stop)
        # Stop daemons.
        gprintf "Shutting down ntpd: "
	killproc ntpd
	RETVAL=$?
        echo
	if [ "$RETVAL" = "0" ]; then
		rm -f /var/lock/subsys/ntpd
	fi
        ;;
  status)
	status ntpd
	RETVAL=$?
	;;
  restart)
	$0 stop
	$0 start
	;;
  reload)
	$0 stop
	$0 start
	;;
  condrestart)
    if [ -f /var/lock/subsys/ntpd ]; then
        $0 stop
        $0 start
    fi
    ;;
  *)
        gprintf "Usage: ntpd {start|stop|restart|reload|status}\n"
        exit 1
esac

exit $RETVAL
