#! /bin/sh

local NAME DESCRIPTION DAEMON

NAME=ntpd
SCRIPTNAME=ntp
DESCRIPTION="OpenNTPD"
DAEMON=/usr/sbin/$NAME

. /etc/init.d/functions.sh
. /etc/conf.d/$SCRIPTNAME || error "/etc/conf.d/$SCRIPTNAME missing"

[ -f $RCLIB/sh/rc-dhcp.sh ] && . $RCLIB/sh/rc-dhcp.sh
[ -f $RCLIB/sh/rc-dhcp6.sh ] && . $RCLIB/sh/rc-dhcp6.sh

NTPD_CONFIG=/var/run/ntpd/ntpd.conf

. /etc/sysconfig/openntpd.conf

# Lock file
_lockf="openntpd"

unlock() {
	remove_lock_file "$_lockf"
}

lock() {
	trap unlock EXIT QUIT INT TERM
	create_lock_file "$_lockf"
}

build_ntpd_config()
{
	rm -f $NTPD_CONFIG
	if [ "$OBTAIN_FROM_DHCP" = yes ]; then
		[ -f "$DHCP6_NTP_CONF" ] && . $DHCP6_NTP_CONF
		[ -f "$DHCP4_NTP_CONF" ] && . $DHCP4_NTP_CONF

		[ "$NTP_SERVERS" ] || [ "$NTP6_SERVERS" ] && {
			for SERVER in $NTP_SERVERS $NTP6_SERVERS; do
				echo "server $SERVER" >> $NTPD_CONFIG
			done
			return 0
		}
	fi
	# Fall back to the manually configured server if none were
	# gotten from DHCP.
	if [ -n "$NTPSERVER" ] && [ "$NTPSERVER" != "0.0.0.0" ]; then
		echo "servers $NTPSERVER" > $NTPD_CONFIG
		return 0
	fi
	return 1
}

start_ntpd () {
	[ "$SYNCSOURCE" = NTP ] || {
		information "NTP time synchronization is not enabled"
		end 0
		exit 0
	}
	if [ "$(pidof $NAME)" ]; then
		information "NTP daemon already started"
		exit 0
	fi
	build_ntpd_config || {
		information "NTP daemon not started. NTP needs to be set first"
		exit 0
	}
	start_daemon_oknodo $DAEMON $NTPD_OPTIONS -f $NTPD_CONFIG
}

stop_ntpd () {
	stop_daemon $DAEMON
}

lock
case "$1" in
	start)
		begin "Starting $DESCRIPTION"
		start_ntpd
		end $?
		;;
	stop)
		begin "Stopping $DESCRIPTION"
		stop_ntpd
		end $?
		;;
	restart)
		begin "Restarting $DESCRIPTION"
		stop_ntpd && start_ntpd
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac
unlock

exit 0
