#! /bin/sh
### BEGIN INIT INFO
# Provides:          vnstat
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: lightweight network traffic monitor
### END INIT INFO

PATH=/usr/sbin:/usr/bin:/sbin:/bin
DESC="vnStat daemon"
NAME=vnstatd
PIDFILE=/run/vnstat/vnstat.pid
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS="-d --pidfile $PIDFILE"
SCRIPTNAME=/etc/init.d/vnstat
USER=vnstat

. /lib/lsb/init-functions

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

case "$1" in
	start)
		log_daemon_msg "Starting $DESC" "$NAME"
		if [ ! -d /run/vnstat ]; then
			mkdir /run/vnstat
		fi
		chown $USER:$USER /run/vnstat
		start-stop-daemon --start --quiet --oknodo --chuid $USER \
			--exec $DAEMON -- $DAEMON_ARGS
		log_end_msg $?
		;;
	stop)
		log_daemon_msg "Stopping $DESC" "$NAME"
		start-stop-daemon --stop --quiet --oknodo --retry=TERM/15/KILL/5 --pidfile $PIDFILE \
			--name $NAME
		status=$?
		rm -f $PIDFILE
		log_end_msg $?
		;;
	status)
		pidofproc -p $PIDFILE $DAEMON >/dev/null
		status=$?

		if [ $status -eq 0 ]; then
			log_success_msg "$DESC is running"
		else
			log_failure_msg "$DESC is not running"
		fi
		exit $status
		;;
	reload|force-reload)
		log_daemon_msg "Reloading $DESC configuration..."
		start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
		log_end_msg $?
		;;
	restart)
		$0 stop
		sleep 1
		$0 start
		;;
	*)
		echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload|status}"
		exit 1
		;;
esac
