#!/bin/sh

# Only run once
[ -n "${POST_UPGRADE_CACHE}" ] && touch "${POST_UPGRADE_CACHE}/`basename $0`"

# in the old scheme, there was no "start_ntp" setting in timing.local
TIMING_CF="/etc/conf.d/timing.local"
if [ -e "${TIMING_CF}" ]
then
	grep -q "start_ntp" "${TIMING_CF}" && exit 0
fi
NTP_CF="/etc/ntp.conf.local"
[ -e "${NTP_CF}" ] || return 0




# We need to upgrade. Old mode was either "manual" or "NTP", with "NTP" being
# used to cover a number of scenarios.
echo " * Upgrading system timing configuration files."



# mode is $1, start_ntp is $2, start_ntpshmgsl is $3
write_new_config() {
	cat > "${TIMING_CF}.new" <<EOF
# /etc/conf.d/timing.local
#  Converted at `isodate -me` by $0

mode = $1
start_ntp = $2
start_ntpshmgsl = $3
EOF
	if [ $? -eq 0 ]
	then
		mv "${TIMING_CF}.new" "${TIMING_CF}"
		[ $? -eq 0 ] && return 0
	fi
	rm -f "${TIMING_CF}.new"
	return 1
}

# $1 is thing managing the SHM segment, $2 the refid
write_ntpshm_config() {
	cat > "${NTP_CF}.new" <<EOF
# /etc/ntp.conf.local
#  Converted at `isodate -me` by $0

driftfile /var/lib/ntp/ntp.drift
restrict default nomodify nopeer
restrict 127.0.0.1

# SHM managed by $1
server 127.127.28.1 minpoll 4 maxpoll 4
fudge 127.127.28.1 refid $2
EOF
	if [ $? -eq 0 ]
	then
		mv "${NTP_CF}.new" "${NTP_CF}"
		[ $? -eq 0 ] && return 0
	fi
	rm -f "${NTP_CF}.new"
	return 1
}


# first, deal with manual mode
if [ -e "${TIMING_CF}" ]
then
	if [ "`gcs_rwvar gcs_get_varcf "timing_source" "${TIMING_CF}"`" = "manual" ]
	then
		echo "  - manual mode"
		write_new_config "manual" "false" "false"
		exit $?
	fi
fi

# search for old NMEA refclock driver (not on CMG-EAM!)
. "/etc/system_type"
if [ "${BUILD_MACHINE}" != "CMG-DCM-mk4-eabi" ]
then
	if grep -q "[^#]*server[^#]*127\\.127\\.20\\." "${NTP_CF}"
	then
		echo "  - NTP peer with GPS reference"
		write_ntpshm_config "gpsd" "GPS"
		write_new_config "direct_gps" "true" "false"
		exit $?
	fi
fi

# search for old GSL refclock driver
if grep -q "[^#]*server[^#]*127\\.127\\.45\\." "${NTP_CF}"
then
	echo "  - CD24/DM24 GPS"
	write_ntpshm_config "ntpshmgsl" "GSL"
	write_new_config "dm24_gps" "true" "true"
	exit $?
fi

# assume pure NTP mode
echo "  - NTP networked mode"
write_new_config "ntp" "true" "false"
exit $?
