#!/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
TIME1_CORRECTION=0.0

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

[ -e /usr/local/etc/telem/gps_time1_correction ] && TIME1_CORRECTION=$(cat /usr/local/etc/telem/gps_time1_correction)

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 &
    
    echo "# THIS FILE IS AUTOMATICALLY GENERATED, ALL CHANGES TO THIS FILE WILL BE LOST!" > $CONFIGFILE
    
    cat /etc/ntp.conf >> $CONFIGFILE
    
    echo "
# GPS sync with NMEA and PPS kernel discipline
    
# GPS synchronization with NMEA data and kernel PPS
server 127.127.20.0 mode 17 minpoll 4 maxpoll 4 prefer
fudge 127.127.20.0 time1 $TIME1_CORRECTION time2 0.133 flag1 1 flag3 1
" >> $CONFIGFILE
    
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"
