#!/bin/sh
#
# Start and stop the distributed.net client.
# Noel@debian.org, 2001-12-16

set -e

DAEMON="/usr/bin/distributed-net"
OPTION="-ini /etc/distributed-net.conf \
	-inbase /var/lib/distributed-net/buff-in \
	-outbase /var/lib/distributed-net/buff-out"

test -x $DAEMON || exit 0

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

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

		# Check if there is a process running as user daemon.
		# There's no pidfile because it's not possible to have
		# one and su to daemon as well.
		if start-stop-daemon --quiet --stop --signal 0 \
			--user daemon \
			--name distributed-net 2>/dev/null
		then
			echo " already running."
			exit
		fi

		su daemon -c "$DAEMON $OPTION &" \
			>> /var/log/distributed-net.log 2>&1 

		echo "."
		;;
	stop)
		echo "Stopping distributed.net client: distributed-net"

		# Check if there is a process running as user daemon.
		# There's no pidfile because it's not possible to have
		# one and su to daemon as well.
		if start-stop-daemon --quiet --stop --signal 0 \
			--user daemon \
			--name distributed-net 2>/dev/null
		then
			#using the builtin "-shutdown" command to end all threads
			cd /var/lib/distributed-net || exit 1

			su daemon -c "$DAEMON $OPTION -shutdown" 2>&1

			#This ensures that distributed-net actually stops
			while start-stop-daemon --quiet --stop --signal 0 --user daemon \
				--name distributed-net 2>/dev/null
			do
				sleep 1
			done
		else
			echo " not running."
		fi
		;;
	force-reload|restart)
		# -HUP has no effect on the client.
		# Check if the daemon is actually running.
		if start-stop-daemon --quiet --stop --signal 0 \
			--user daemon \
			--name distributed-net \
			2>/dev/null
			
		then
			$0 stop
			#We used to have a wait-loop in here. Now it's
			#in stop, so d-net /always/ stops.
			$0 start
		fi
		;;
        fetch)
                # Note: cannot use /usr/bin/distributed-net since that
                # will expect .ini file to also be in /usr/bin
                echo -n "Distributed.net: Fetching blocks"
                cd /var/lib/distributed-net || exit 1
                su daemon -c "$DAEMON $OPTION -fetch"
                ;;
        flush)
                echo -n "Distributed.net: Flushing blocks"
                cd /var/lib/distributed-net || exit 1
                su daemon -c "$DAEMON $OPTION -flush"   
                ;;  
        update)
                echo -n "Distributed.net: Updating blocks"
                cd /var/lib/distributed-net || exit 1
                su daemon -c "$DAEMON $OPTION -update"
		;;
	*)
		echo "Usage: /etc/init.d/distributed-net {start|stop|restart|force-reload|fetch|flush|update}"
		exit 1
esac

exit 0
