#!/bin/sh
gpsd="$1"
options="$2"
device="$3"
waitforchronyd="$4"

#gpsd=/usr/local/sbin/gpsd
#options=""
#device=/dev/tty.usbserial-1460
#waitforchronyd=1

LOG=/tmp/gpsdstart.log

date > $LOG
echo gpsd: $gpsd >> $LOG
echo options: $options >> $LOG
echo device: $device >> $LOG
echo waitforchronyd: $waitforchronyd >> $LOG

if [ $waitforchronyd == 1 ]; then
	#
	# spin our wheels until chronyd is running
	#
	count=0
	pid=0
	until [ $count -gt 100 ]
	do
		count=$(($count + 1))
		pid=$(pgrep chronyd)
		if [ $? == 0 ]; then
			break
		fi
		echo Waiting for chronyd >> $LOG
		sleep 1
	done
	if [ -n "$pid" ]; then
		echo chronyd is running with pid: $pid >> $LOG
	else
		echo "Waited $count seconds for chronyd - giving up" >> $LOG
	fi

	#
	# wait 2 seconds to allow chrony to initialise
	#
	sleep 2
fi

#
# run gpsd in the foreground so launchd will retain control
#
date >> $LOG
echo "Starting: $gpsd -N -n $options $device" >> $LOG
exec $gpsd -N -n $options $device
