#!/bin/sh

# this script, starts and stops the communication between spacenavd and the
# local X server. (:0).

if [ "$1" != 'x11' ]; then
	echo "the only valid control for the moment is x11 ($0 x11 start/stop)."
	exit 1
fi

if [ -z "$2" ]; then
	echo 'you must specify either "start" or "stop".'
	exit 1
fi

if [ "$2" = 'start' ]; then
	# check to see there is a local X server running.
	DISPLAY=":0"
	xdpyinfo >/dev/null 2>/dev/null
	if [ $? != 0 ]; then
		echo "You must have an X server running before starting up spacenavd-X11 events."
		exit 1
	fi
	sig=-usr1

elif [ "$2" = "stop" ]; then
	sig=-usr2

else
	echo 'you must specify either "start" or "stop".'
	exit 1
fi

# detect daemon's process id
pid=`cat /var/run/spnavd.pid 2>/dev/null`
if [ $? != 0 ]; then
	pid=`ps -e | grep spacenavd | awk '{ print $1 }'`
	if [ -z "$pid" ]; then
		echo 'spacenavd daemon is not running, nothing to do.'
		exit 1
	fi
fi

kill $sig $pid
if [ $? = 0 ]; then
	if [ $sig = '-usr1' ]; then
		echo 'signalled spacenavd, it should now start sending X events.'
	else
		echo 'signalled spacenavd to stop sending X events.'
	fi
else
	echo 'sending signal to spacenavd failed.'
fi
