#! /bin/sh
#
# init script for gpio pps
#

. /usr/local/bin/telem/gps_functions
isGPSttyEnabled || exit 0

initNMEA() {
    ln -s "${TTY_GPS}" "/dev/gps0"
    ln -s "${DEV_PPS}" "/dev/gpspps0"
}

write(){
    printf "\x$(echo "$1" | sed 's; ;\\x;g')" > "${TTY_GPS}"
    usleep 100000
}

initGW6RTC() {
    ln -s "${TTY_GPS}" "/dev/refclock-0"
    #ln -s "${DEV_PPS}" "/dev/refclockpps-0"
    
    # port will die if you do not read
    cat "${TTY_GPS}" > /dev/null &
    stty -F "${TTY_GPS}" 0:0:8bd:0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0
    
    # Identification (0x99)
    write "C0 08 99 7F C0"
    write "C0 08 99 30 00 51 C0"
    # config GPS (0x30) port optical (0x00)
    write "C0 08 30 00 83 C0"
    
    sleep 1
    # kill reader
    kill "$!"
}

start() {
    echo "Loading pps modules (pps_core pps-gpio)"
    modprobe pps_core
    modprobe pps-gpio
    
    initGPSVarAll

    echo "Setting up devices for gps and pps"
    
    "init${GPSTYPE}"
}

case "$1" in
    start)
        start
        ;;
    stop)
        : # do nothing
        ;;
    *)
        echo "Usage: $0 {start}"
        exit 1
esac

exit $?
