#!/bin/sh

### BEGIN INIT INFO
# Provides:		gnunet-server
# Required-Start:	$syslog $network $local_fs $remote_fs
# Required-Stop:	$syslog $network $local_fs $remote_fs
# Should-Start:
# Should-Stop:
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Starts the GNUnet server at boot time.
# Description:		GNUnet is a secure, trust-based peer-to-peer framework.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/gnunetd
NAME=gnunetd
DESC=GNUnet
# Assuming default value for PIDFILE. This should not be changed
PIDFILE=/var/run/gnunetd/"${NAME}".pid

test -x "${DAEMON}" || exit 0

set -e

# Get configuration
if [ -f /etc/default/gnunet-server ]
then
	. /etc/default/gnunet-server
fi

if [ "${GNUNET_AUTOSTART}" != "true" ]
then
	exit 0
fi

# Check if /var/run/gnunetd exists (in case /var/run is on tmpfs)
if ! [ -d /var/run/gnunetd ]
then
	mkdir -p /var/run/gnunetd
	chown ${GNUNET_USER}:${GNUNET_GROUP} /var/run/gnunetd -R
fi

case "${1}" in
	start)
		# We should not need --background, but if not here, the
		# invoke-rc.d hangs when using debconf --quiet removed: For some
		# unknown reason, with gnunet 0.7.0, adding --quiet brake the
		# pidfile creation...

		echo -n "Starting ${DESC}: "
		start-stop-daemon --start --background --chuid ${GNUNET_USER} \
			--pidfile "${PIDFILE}" --exec ${DAEMON} -- -c \
			/etc/gnunetd.conf
		echo "${NAME}."
		;;

	stop)
		echo -n "Stopping ${DESC}: "
		start-stop-daemon --stop --pidfile ${PIDFILE} --exec ${DAEMON} \
			--retry 15 --oknodo
		echo "${NAME}."
		;;

	restart|force-reload)
		${0} stop
		sleep 1
		${0} start
		;;

	*)
		echo "Usage: ${0} {start|stop|restart|force-reload}" >&2
		exit 1
		;;
esac

exit 0
