#!/bin/sh
#
#		init.d script for BandwidthD
#		Andreas Henriksson <andreas@fjortis.info>
#
#

DAEMON=/usr/sbin/bandwidthd
WORKDIR=/var/lib/bandwidthd
CONFFILE=/etc/bandwidthd/bandwidthd.conf
NAME=bandwidthd
DESC=BandwidthD
PIDFILE=/var/run/$NAME.pid

test -x $DAEMON || exit 0


function checkconfig () {
	# abort if we detect an unconfigured bandwidthd-pgsql config.
	if [ $(grep -c1 "pgsql_connect_string \"user = someuser dbname = mydb host = localhost\"" $CONFFILE) != 0 ]; then

		echo ""
		echo "ATTENTION!"
		echo "You have to manually add the postgresql-user, database and tables."
		echo "(Schema available at /usr/share/doc/bandwidthd-pgsql/schema.postgresql)"
		echo "You also have to edit /etc/bandwidthd/bandwidthd.conf to specify which database the sensor should log to. If you want to run the web-interface on this computer you also need to edit /var/lib/bandwidthd/htdocs/config.conf to specify the postgresql-connection settings there and create a symlink from your webroot to the htdocs directory."
		echo ""

		exit 0
	fi
	
	# abort if the config doesn't have a device set up.
	if [ $(grep -c1 "^[^#].*d*ev " $CONFFILE) = 0 ]; then
		echo "Skipping $DESC: Please edit $CONFFILE."
		exit 0
	fi
}

function startd () {
	# Woodys start-stop-daemon doesn't support --chdir but Sarges require it.
	if [ "$(cat /etc/debian_version)" == "3.0" ]; then
		CHDIR=""
	else
		CHDIR="--chdir $WORKDIR"
	fi

	echo -n "Starting $DESC: "
	cd $WORKDIR && start-stop-daemon --start --quiet \
		--pidfile $PIDFILE \
		$CHDIR \
		--exec $DAEMON -- $DAEMON_OPTS
	if [ $? -ne 0 ]; then
		echo "failed."
	else
		echo "$NAME."
	fi
}

function stopd () {
	echo -n "Stopping $DESC: "
	start-stop-daemon --stop --quiet --signal TERM \
		--pidfile $PIDFILE --exec $DAEMON
	if [ $? -ne 0 ]; then
		echo "failed."
	else
		echo "$NAME."
	fi
}

function restartd () {
	stopd
	sleep 1
	startd
}

function rotatelogs () {
	echo -n "Rotating logs for $DESC: "
	start-stop-daemon --stop --quiet --signal HUP \
		--pidfile $PIDFILE --exec $DAEMON
	if [ $? -ne 0 ]; then
		echo "failed."
	else
		echo "$NAME."
	fi
}


case "$1" in
  start)
    checkconfig
	startd
	;;
  stop)
	stopd
	;;
  rotate)
	rotatelogs
    ;;
  restart|force-reload)
	checkconfig
	restartd
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|rotate|force-reload}" >&2
	exit 1
	;;
esac

exit 0
