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

NAME=ntpd
script=ntp
DAEMON=/usr/sbin/$NAME
RUNDIR=/run/ntp
NC=$RUNDIR/ntpd.conf
PID=$RUNDIR/ntpd.pid
ARG_FILE=$RUNDIR/ntpd.cmd_arg

. /etc/init.d/functions.sh

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() {
	remove_lock_file $LF
}

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

# Saves a list of ntp servers to $1
get_dhcp_conf() {
	[ $# -eq 1 ] ||
		error "$0: get_dhcp_conf: Wrong number of arguments"
	local s c=
	[ "$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
	}
	eval $1=\$c
}

# Saves a list of ntp servers to $1
get_ntp_servers() {
	[ $# -eq 1 ] ||
		error "$0: get_ntp_servers: Wrong number of arguments"
	local server
	get_dhcp_conf server
	[ -n "$server" ] || {
        for SERVER in $NTPSERVER; do
		    server=$server"servers $SERVER
"
        done
        server=$server"listen on *
"
    }
	eval $1=\$server
}

ntp_to_be_started() {
	lock
	local dhcp_server ret_val=1
	if [ "$SYNCSOURCE" = NTP ] ; then
		get_dhcp_conf dhcp_server
		[ -z "$dhcp_server" ] ||
			ret_val=0

		[ -z "$NTPSERVER" ] || [ "$NTPSERVER" = 0.0.0.0 ] ||
			ret_val=0
	fi
	return $ret_val
}
