#!/bin/sh
#
# pmacct
#
# chkconfig: 2345 60 40
# description:	Starts, stops and saves pmacct (all instances)
#
# config: /usr/etc/*.conf

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

daemondir=/usr/sbin
path_to_etc=/etc/pmacct
path_to_lock=/var/run/pmacct
path_to_pid=/var/run/pmacct

unset ORDER

for f in $path_to_etc/*.conf; do
	NAME=$(basename $f)
	NAME=$(echo $NAME | sed -e 's,\(\w*\)\.conf,\1,g')
	ORDER="$ORDER $NAME"
done

unset NAME

start() {
#	sleep 3
	RETVAL=0
	[ -d /var/run/pmacct ] || /bin/mkdir -p /var/run/pmacct;
	if [ -x $daemondir/pmacctd ] ; then
		for i in $ORDER; do
			start_daemon \
				--pidfile "$path_to_pid/$i.pid" \
				--lockfile "$path_to_lock/$i.lock" \
				--displayname $i \
				-- $daemondir/pmacctd -f $path_to_etc/$i.conf
			RETVAL=$RETVAL || $?
		done
	else
		RETVAL=1
		echo "Starting pmacct:"
		failure
		echo
	fi
	return $RETVAL
}

stop() {
	RETVAL=0
	for i in $ORDER; do
		stop_daemon \
			--pidfile "$path_to_pid/$i.pid" \
			--lockfile "$path_to_lock/$i.lock" \
			--displayname $i \
			-- pmacctd
		RETVAL=$RETVAL || $?
	done
	killall pmacctd
	return $RETVAL
}

stat() {
	RETVAL=0
	for i in $ORDER; do
		status \
			--pidfile "$path_to_pid/$i.pid" \
			--lockfile "$path_to_lock/$i.lock" \
			--displayname $i \
			-- pmacctd
		RETVAL=$RETVAL || $?
	done
	return $RETVAL
}

case "$1" in

start)
	start
	;;

stop)
	stop
    ;;
restart)
    stop
    start
    ;;
status)
	stat
    ;;
*)
	msg_usage "${0##*/} {start|stop|restart|status}"
	RETVAL=1
    ;;

esac

exit $RETVAL