#!/bin/sh
# ntp hotplug script for travelmate
# Copyright (c) 2020 Dirk Brenken (dev@brenken.org)
# This is free software, licensed under the GNU General Public License v3.

# set (s)hellcheck exceptions
# shellcheck disable=1091,2016,2039,2059,2086,2143,2181,2188

trm_init="/etc/init.d/travelmate"
trm_ntpfile="/var/state/travelmate.ntp"
trm_logger="$(command -v logger)"

f_log()
{
	local class="${1}" log_msg="${2}"

	if [ -x "${trm_logger}" ]
	then
		"${trm_logger}" -p "${class}" -t "trm-ntp  [${$}]" "${log_msg}"
	else
		printf "%s %s %s\\n" "${class}" "trm-ntp  [${$}]" "${log_msg}"
	fi
}

if [ "${ACTION}" = "stratum" ] && [ ! -f "${trm_ntpfile}" ] && [ "$("${trm_init}" enabled; printf "%u" ${?})" = "0" ]
then
	{
		flock -xn 1001
		if [ "$?" = "0" ]
		then
			f_log "info" "get ntp time sync"
			"${trm_init}" restart
		fi
	} 1001>"${trm_ntpfile}"
fi
