#!/bin/sh
# /etc/init.d/gps
#
### BEGIN INIT INFO
# Provides:          gps
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     5
# Default-Stop:      0 6
# Short-Description: GPS gpio control
# Description:       Enables onboard GPS engine
### END INIT INFO

GPS_RESET_N=72
PLATFORM=`cat /etc/raven/platform`

DAEMON=/usr/sbin/gps-parse.py
DAEMONOPTS=""
NAME=gps-parse.py

set_gpio()
{
	if [ ! -d /sys/class/gpio/gpio$1 ]; then
		echo $1 > /sys/class/gpio/export
		
		if [ $2 -eq 1 ]; then
			echo high > /sys/class/gpio/gpio$1/direction
		else
			echo low > /sys/class/gpio/gpio$1/direction
		fi
	fi
	
	echo $2 > /sys/class/gpio/gpio$1/value
}

case "$1" in
  start)
	echo 09d7 0100 >/sys/bus/usb-serial/drivers/generic/new_id

#attempted fix at having rtk startup issues by forcing a reboot of the card 
	if [ "${PLATFORM}" = "PINEHURST" ]; then
		set_gpio ${GPS_RESET_N} 0
		sleep 3
	fi

	set_gpio ${GPS_RESET_N} 1
    
    if [ "${PLATFORM}" = "PINEHURST" ]; then
	   if [ "$2" = "nocheck" ]; then
           echo "Starting gps but skipping check"    
	   else
           /usr/sbin/gpscheck &
       fi
    fi
  ;;
  stop)

	if [ "${PLATFORM}" = "PINEHURST" ]; then
		exit 0    #no need to control reset lines on pinehurst
	fi

	set_gpio ${GPS_RESET_N} 0
  ;;
  usb)
	echo 09d7 0100 >/sys/bus/usb-serial/drivers/generic/new_id
  ;;
  reset)
	set_gpio ${GPS_RESET_N} 0
	set_gpio ${GPS_RESET_N} 1
  ;;
  realtimestart)
	echo -n "Starting app: $NAME  "

    [ -d /var/run/${NAME} ] || mkdir -p /var/run/${NAME}
	start-stop-daemon --start --background -m --pidfile /var/run/${NAME}/${NAME}.pid --exec ${DAEMON} -- ${DAEMONOPTS}
    echo "."
  ;;
  realtimestop)

	if [ -f /var/run/${NAME}/${NAME}.pid ]; then
   		PID=`cat /var/run/${NAME}/${NAME}.pid` ##TODO,, this is not safe if it crashed as something else may have pid, but python and start/stop have issues
	
		kill ${PID}
		rm -f /var/run/${NAME}/${NAME}.pid
	fi
  ;;
  *)
	echo "Usage /etc/init.d/gps [start|stop|reset]"
	exit -1
  ;;
esac

exit 0
