#!/bin/sh -e
#
# 2020 Dennis Camera (dennis.camera@ssrq-sds-fds.ch)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

mode=$(cat "${__object:?}/parameter/mode")

timedatectl_localrtc=$(cat "${__object:?}/explorer/timedatectl_localrtc")
adjtime_mode=$(cat "${__object:?}/explorer/adjtime_mode")


case ${mode}
in
	(localtime)
		adjtime_str=LOCAL
		local_rtc_str=yes
		;;
	(UTC|utc)
		adjtime_str=UTC
		local_rtc_str=no
		;;
	(*)
		printf 'Invalid value for --mode: %s\n' "${mode}" >&2
		printf 'Acceptable values are: localtime, utc.\n' >&2
		exit 1
esac


if test -n "${timedatectl_localrtc}"
then
	# systemd
	timedatectl_should=${local_rtc_str}
	if test "${timedatectl_localrtc}" != "${timedatectl_should}"
	then
		printf 'timedatectl set-local-rtc %s\n' "${timedatectl_should}"
	fi
elif test -n "${adjtime_mode}"
then
	# others (update /etc/adjtime if present)
	if test "${adjtime_mode}" != "${adjtime_str}"
	then
		# Update /etc/adjtime (3rd line is clock mode)
		# adjtime(5) https://man7.org/linux/man-pages/man5/adjtime.5.html
		# FIXME: Should maybe add third line if adjfile only contains two lines
		printf "sed -i '3c\\\\\\n%s\\n' /etc/adjtime\\n" "${adjtime_str}"
	fi
fi
