#!/bin/sh

# ntpd options
# -n Don't fork. So returns can be logged.
# -g This option allows the time to be set to any value without restriction; however, this can happen only once.
# -x Normally, the time is slewed if the offset is less than the step threshold, which is 128 ms by default, and stepped if above the threshold.
#    This option sets the threshold to 600 s, which is well within the accuracy window to set the clock manually. 

CONFIGFILE=/etc/ntp.conf
GPSENABLED=no
PORT=CNone

[ -e /etc/telem-gps.conf ] && . /etc/telem-gps.conf

if [ "x$GPSENABLED" = "xyes" ] && [ "x$PORT" = "xC1" ]; then
    CONFIGFILE=/etc/ntp-run.conf
    
    touch /var/local/telem/gps_is_enabled
    touch /var/local/telem/errors/gps_invalid
    
    killall check_gps_status
    /usr/local/bin/ntp/check_gps_status &    
fi

while true
do
    logger "Starting NTP daemon"
    ntpd -n -g -x -c $CONFIGFILE
    hwclock -w -u
    logger "NTP daemon failed, restarting in 2 seconds"
    sleep 2
done

echo "Done"
