#!/bin/sh -e
# Copyright (c) 2007-2012 Axis Communications AB

NAME=ntpd
script=ntp
desc=OpenNTPD
DAEMON=/usr/sbin/$NAME
NC=/var/run/ntpd/ntpd.conf

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

sf=$RCLIB/sh/rc-dhcp.sh
[ ! -r $sf ] || . $sf || error "Source '$sf' failed"
sf=$RCLIB/sh/rc-dhcp6.sh
[ ! -r $sf ] || . $sf || error "Source '$sf' failed"

sf=/etc/sysconfig/openntpd.conf
. $sf || error "Source '$sf' failed"

LF="openntpd"

unlock() {
	local e=$?
	remove_lock_file $LF
	end $e
}

lock() {
	trap unlock EXIT
	trap exit QUIT INT TERM HUP
	create_lock_file $LF
}

build_config() {
	local s c=
	rm -f $NC
	[ "$OBTAIN_FROM_DHCP" != yes ] || {
		[ ! -r "$DHCP6_NTP_CONF" ] || . $DHCP6_NTP_CONF ||
			warning "Could not source '$DHCP6_NTP_CONF'"
		[ ! -r "$DHCP4_NTP_CONF" ] || . $DHCP4_NTP_CONF ||
			warning "Could not source '$DHCP4_NTP_CONF'"
		for s in $NTP_SERVERS $NTP6_SERVERS; do
			c=$c"server $s
"
		done
	}
	[ "$c" ] || [ -z "$NTPSERVER" ] || [ "$NTPSERVER" = 0.0.0.0 ] || {
		for SERVER in $NTPSERVER; do
			c=$c"servers $SERVER
"
		done
		c=$c"listen on *
"
	}

	[ "$c" ] || return 1
	printf "%s" "$c">$NC
}

build_ntpd_config()
{
	build_config
}

start_ntpd () {
	[ "$SYNCSOURCE" = NTP ] || {
		information "NTP time synchronization is not enabled"
		exit 0
	}
	! pidof $NAME >/dev/null 2>&1 || {
		information "NTP daemon already started"
		exit 0
	}
	build_config || {
		information "NTP daemon not started. NTP needs to be set first"
		exit 0
	}
	start_daemon_oknodo $DAEMON $NTPD_OPTIONS -f $NC
}

stop_ntpd () {
	local ps to=120 pf=/var/run/ntpd.pid
	stop_daemon $DAEMON || warning "Could not stop '$DAEMON'"
	while ps=$(pidof $NAME); do
		to=$(($to-1))
		[ $to -gt 0 ] || {
			warning "$NAME child process never terminated."
			break
		}
		kill -TERM $ps >/dev/null 2>&1 ||:
		sleep 1
	done
	[ ! -e $pf ] || rm -f $pf
}

lock
case "$1" in
	start)
		begin "Starting $desc"
		start_ntpd
		;;
	stop)
		begin "Stopping $desc"
		stop_ntpd
		;;
	restart)
		begin "Restarting $desc"
		stop_ntpd && start_ntpd
		;;
	*)
		error "Usage: $0 {start|stop|restart}"
		;;
esac
