#!/bin/sh
#
# munin-asyncd	Start/Stop the munin-asyncd daemon.
#
# chkconfig:	2345 91 09
# description:	munin-asyncd enables asyncronous fetching of
#		metrics from munin-node in a Munin monitoring setup.
#
# processname:	munin-asyncd
# pidfile:	/var/run/munin-asyncd.pid
#
### BEGIN INIT INFO
# Provides:		munin-asyncd
# 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:	Starts and stops munin-asyncd
# Description:		munin-asyncd enables asyncronous fetching of
#			metrics from munin-node in a Munin monitoring setup.
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

# Get config
. /etc/sysconfig/munin-asyncd

# Set defaults in case they're not defined in config
MUNIN_NODE_HOST=${MUNIN_NODE_HOST:-localhost}
MUNIN_NODE_PORT=${MUNIN_NODE_HOST:-4949}
MUNIN_ASYNCD_SHUTDOWN_TIMEOUT=${MUNIN_ASYNCD_SHUTDOWN_TIMEOUT:-15}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/munin-asyncd ]; then
		msg_already_running "Munin Asyncd"
		return
	fi

	msg_starting "Munin Asyncd"
	daemon --fork /usr/sbin/munin-asyncd --host ${MUNIN_NODE_HOST}:${MUNIN_NODE_PORT}
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/munin-asyncd
}

stop() {
	if [ ! -f /var/lock/subsys/munin-asyncd ]; then
		msg_not_running "Munin Asyncd"
		return
	fi

	msg_stopping "Munin Asyncd"
	busy
	# We can't kill by process name, asyncd is changing it dynamically
	# so we simply send TERM to all asyncd processes
	for ppid in $(pgrep "^munin-asyncd "); do
		kill -TERM ${ppid}
	done
	timeout=0
	while pgrep "^munin-asyncd " 1>/dev/null 2>&1; do
		# If timeout was reached send kill signal and break loop
		if [ $timeout -ge $MUNIN_ASYNCD_SHUTDOWN_TIMEOUT ]; then
			for ppid in $(pgrep "^munin-asyncd "); do
				kill -KILL ${ppid}
			done
			break
		fi
		sleep 1
		timeout=$((timeout+1))
	done
	ok
	rm -f /var/lock/subsys/munin-asyncd
}

condrestart() {
	if [ ! -f /var/lock/subsys/munin-asyncd ]; then
		msg_not_running "Munin Asyncd"
		RETVAL=$1
		return
	fi

	stop
	start
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|reload|force-reload)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  status)
	status --pidfile /var/run/munin-asyncd.pid munin-asyncd
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|reload|force-reload|status}"
	exit 3
esac

exit $RETVAL
