#!/bin/sh
# Build ntp.conf or ntpd.conf and restart ntpd
# Based on dhcpcd hook script
# (C) Copyright 2009-2015 Mikhail Efremov

. /usr/lib/NetworkManager/nm-dispatcher-sh-functions

if nm_skip_hook "${0##*/}"; then
	exit 0
fi

if [ -x /etc/init.d/ntpd ]; then
	ntpd_restart_cmd="/sbin/service ntpd condrestart >/dev/null 2>&1"
fi

signature_begin="# Generated by NetworkManager from"
signature_end="# End of NetworkManager from"

remove_generated()
{
	local interface="$1";shift
	local ntp_conf="$1";shift

	[ -n "${interface}" -a -w "${ntp_conf}" ] || return 1

	grep -qs "^${signature_begin} ${interface}" "${ntp_conf}" || return 1

	sed -i "/^${signature_begin} ${interface}/,/^${signature_end} ${interface}/d" "${ntp_conf}"
}

build_ntp_conf()
{
	local interface="$1";shift
	local ntp_conf="$1";shift
	local server_keyword=${1:-server}
	local header= srvs= servers= x= i=

	[ -n "${interface}" -a -w "${ntp_conf}" ] || return 1

	for x in ${DHCP4_NTP_SERVERS}; do
		egrep -qs "^server[s]?[[:space:]]+${x}" "${ntp_conf}" ||
		servers="${servers}${server_keyword} ${x}\n"
	done

	[ -n "${servers}" ] || return 1

	local cf="$(mktemp -t "nm-${ntp_conf##*/}.XXXXXX")"
	remove_generated "${interface}" "${ntp_conf}"
	cat "${ntp_conf}" > "${cf}"
	echo "${signature_begin} ${interface}" >> "${cf}"
	printf "${servers}" >> "${cf}"
	echo "${signature_end} ${interface}" >> "${cf}"
	mv -f "${cf}" "${ntp_conf}"
	chmod 644 "${ntp_conf}"
}

remove_all_generated()
{
	local ret=1

	remove_generated "$1" "/etc/ntpd.conf" && ret=0
	remove_generated "$1" "/etc/ntp.conf" && ret=0

	return ${ret}
}

build_all_ntp_conf()
{
	local ret=1

	[ -n "${DHCP4_NTP_SERVERS}" ] || return 1
	#for openntpd will be used "servers" keyword instead "server"
	build_ntp_conf "$1" "/etc/ntpd.conf" "servers" && ret=0

	build_ntp_conf "$1" "/etc/ntp.conf" && ret=0

	return ${ret}
}

restart_ntpd()
{
	[ -n "${ntpd_restart_cmd}" ] && eval ${ntpd_restart_cmd}
}

case "$2" in
	up) 
	if build_all_ntp_conf "$1"; then
		restart_ntpd
	else
		exit 0
	fi
	;;
	down) 
	if remove_all_generated "$1"; then
		restart_ntpd
	else
		exit 0
	fi
	;;
esac
