#!/bin/sh
# chkconfig: 2345 98 04
# description: Script to control internet traffic.
# processname: shaperd
#
# shaperd $VER: 1.15 (15.11.2003)
#
#		Script to control internet incoming LAN traffic.
#
# Author:       Grzegorz Fitrzyk SP9WUN <sp9wun@poczta.onet.pl>
#

# See how we were called.
RETVAL=0

start() {
        echo -n "Starting shaperd: "
	echo
	for c in `ls -1 /etc/shaper | grep "shaper\.[0123456789]\.cfg$" | cut -d '.' -f2 | cut -d '.' -f1`
	do
	    if [ ! -f /var/run/shaperd.$c.pid ];then
		echo -n "shaperd.$c "
	        /sbin/shaperd -config=$c
		RETVAL=$?
	    fi
	done
	echo
	return $RETVAL
}

stop() {
	echo -n "Shutting down shaperd: "
	echo
	for c in `ls -1 /etc/shaper | grep "shaper\.[0123456789]\.cfg$" | cut -d '.' -f2 | cut -d '.' -f1`
	do
	    if [ -f /var/run/shaperd.$c.pid ];then
		pid=`cat /var/run/shaperd.$c.pid`
		echo -n "shaperd.$c "
		if [ `ps ax | grep shaperd | grep $pid | wc -l` -eq 1 ];then
		    kill $pid 2> /dev/null
		    RETVAL=$?
		    a=0
		    while [ `ps ax | grep shaperd | grep $pid | wc -l` -eq 1 ];do
			echo -n "."
			sleep 1
		        a=`expr $a + 1`
			if [ $a -ge 60 ];then
			    kill -9 $pid 2> /dev/null
			    rm -f /var/run/shaperd.$c.pid
			    echo "-9 killed"
			    break
		        fi
		    done
		    rm -f /var/run/shaperd.$c.pid
		    echo killed
		else
		    rm -f /var/run/shaperd.$c.pid
		    echo "is dead but PID exists - removed PID file."
		fi
	    fi
	done
	return $RETVAL
}

status() {
	echo -n "Status of shaperd: "
	echo
	for c in `ls -1 /etc/shaper | grep "shaper\.[0123456789]\.cfg$" | cut -d '.' -f2 | cut -d '.' -f1`
	do
	    if [ -f /var/run/shaperd.$c.pid ];then
		pid=`cat /var/run/shaperd.$c.pid`
		fin=`ps j $pid | grep shaperd | wc -l`
		if [ $fin -eq 1 ];then
		    echo "shaperd.$c is working"
		else
		    echo "shaperd.$c is'nt working but PID file exists"
		fi
	    else
		echo "shaperd.$c is stopped"
	    fi
	done
        return 1
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
    	start
	RETVAL=$?
	;;
  reload)
	killall -HUP shaperd
	;;
  status)
	status master
	RETVAL=$?
	;;
  *)
	echo "Usage: shaperd {start|stop|restart|reload|status}"

esac

exit $RETVAL

