#!/bin/sh
# Build ntp.conf, ntpd.conf or chrony.conf
# and restart ntp service,
# Based on dhcpcd hook script
# (C) Copyright 2009-2019 Mikhail Efremov <sem@altlinux.org>

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

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

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

ntp_conf_server_word=
NTP_CONF=
ntp_restart_cmd=

init_vars()
{
	local ntp_confs='ntpd.conf ntp.conf chrony.conf'
	local ntp_service= f=

	for f in ${ntp_confs}; do
		if [ -e "/etc/$f" ]; then
			NTP_CONF="/etc/$f"
			break
		fi
	done

	[ -n "$NTP_CONF" ] || exit 0

	# Derive service name from configuration
	case "$NTP_CONF" in
		*/chrony.conf)
			ntp_service=chronyd
			;;
		*/ntpd.conf)
			ntp_service=ntpd
			#for openntpd will be used "servers" keyword instead "server"
			ntp_conf_server_word="servers"
			;;
		*)
			ntp_service=ntpd
			;;
	esac

	if [ -n "$NTP_CONF" ]; then
		ntp_restart_cmd="/sbin/service $ntp_service condrestart"
	fi
}

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 servers= x=

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

	remove_generated "${interface}" "${ntp_conf}"
	for x in $DHCP6_NTP_SERVERS $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")"
	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}"

	# if selinux is enabled, restore file label
	local SELINUXENABLED="selinuxenabled"
	local FIXFILES="fixfiles"
	if type $SELINUXENABLED &>/dev/null && type $FIXFILES &>/dev/null ; then
		$SELINUXENABLED
		if [ $? -eq 0 ] ; then
			$FIXFILES -F restore "${ntp_conf}"
		fi
	fi
}

restart_ntp_service()
{
	[ -n "${ntp_restart_cmd}" ] && eval ${ntp_restart_cmd}
}

case "$2" in
	up)
		init_vars
		if build_ntp_conf "$1" "$NTP_CONF" "$ntp_conf_server_word"; then
			restart_ntp_service
		else
			exit 0
		fi
		;;
	down)
		init_vars
		if remove_generated "$1" "$NTP_CONF"; then
			restart_ntp_service
		else
			exit 0
		fi
		;;
esac
