#!/bin/sh
#
# Start and stop the distributed.net personal proxy.

PPROXY=/usr/lib/distributed-net-pproxy/distributed-net-pproxy

test -x ${PPROXY} || exit 0

case "$1" in
	start)
		echo -n "Starting distributed.net personal proxy: distributed-net-pproxy"
		cd /var/lib/distributed-net-pproxy || exit 1

		# Check if there is a process to match what's in the pid
		# file, by sending signal 0, which has no effect. This 
		# also checks to see if there is a pid file at all, BTW.
		if start-stop-daemon --quiet --stop --signal 0 \
			--pidfile /var/run/distributed-net-pproxy.pid \
			--name distributed-net 2>/dev/null
		then
			echo " already running."
			exit
		fi

		# Figure out where start-stop-daemon is (it's moved between
		# bo and hamm, and it isn't in the path inside a su).
		if [ -x /sbin/start-stop-daemon ]; then
			ssd=/sbin/start-stop-daemon
		else
			ssd=/usr/sbin/start-stop-daemon
		fi

		/bin/su nobody -c "$ssd --start --quiet \
			--exec ./distributed-net-pproxy \
			--pidfile /var/run/distributed-net-pproxy.pid" \
			>>/var/log/distributed-net-pproxy/console.log \
			2>/dev/null &

		echo $! > /var/run/distributed-net-pproxy.pid
		echo "."
		;;
	stop)
		echo -n "Stopping distributed.net personal proxy: distributed-net-pproxy"
		# Check if there is a process to match what's in the 
		# pid file, by sending signal 0, which has no effect.
		# This also checks to see if there is a pid file at 
		# all, BTW.
		if start-stop-daemon --quiet --stop --signal 0 \
			--pidfile /var/run/distributed-net-pproxy.pid --user nobody \
			--name distributed-net 2>/dev/null
		then
			start-stop-daemon --quiet --stop \
				--exec ${PPROXY} \
				--pidfile /var/run/distributed-net-pproxy.pid \
				--user nobody \
				--name distributed-net
			echo "."
		else
			echo " not running."
		fi

		rm -f /var/run/distributed-net-pproxy.pid
		;;
	restart)
		if start-stop-daemon --quiet --stop --signal 0 \
			--pidfile /var/run/distributed-net-pproxy.pid \
			--name distributed-net \
			--user nobody 2>/dev/null
		then
			$0 stop
			sleep 2
			$0 start
		fi
		;;
	force-reload)
		$0 reload
		;;
	reload)
		echo -n "Reloading distributed.net personal proxy configuration..."
		# Check if there is a process to match what's in the 
		# pid file, by sending signal 0, which has no effect.
		# This also checks to see if there is a pid file at 
		# all, BTW.
		if start-stop-daemon --quiet --stop --signal 0 \
			--pidfile /var/run/distributed-net-pproxy.pid --user nobody \
			--name distributed-net 2>/dev/null
		then
			start-stop-daemon --quiet --stop --signal 1 \
				--exec ${PPROXY} \
				--pidfile /var/run/distributed-net-pproxy.pid \
				--user nobody \
				--name distributed-net
			echo "done."
		else
			echo "not running."
		fi
		;;
	*)
		echo "Usage: "$0" {start|stop|restart|reload|force-reload}"
		exit 1
esac

exit 0
