#!/bin/sh

prefix=@prefix@
pkglibdir=@libdir@/@PACKAGE@
pkgdatadir=@datadir@/@PACKAGE@
sysconfdir=@sysconfdir@
pidfiledir=/var/run

#export LD_LIBRARY_PATH=$pkglibdir
export PYTHONPATH=$pkgdatadir/pylib:$sysconfdir
ZORP=$pkglibdir/zorp
INSTANCES=$sysconfdir/instances.conf

start() {
	
	egrep -w "^$1" $INSTANCES | egrep -v "^#|^$" | while read line; do
		set $line
		instance_name=$1
		args="--as $instance_name $@ "
		if [ -r $pidfiledir/zorp-$instance_name.pid ]; then
			pid=`cat $pidfiledir/zorp-$instance_name.pid`
			if kill -CONT $pid >/dev/null 2>/dev/null; then
				# still running
				echo -n "$instance_name! "
			else
				rm $pidfiledir/zorp-$instance_name.pid
				$ZORP $args &
				echo -n "$instance_name "
			fi
		else
			$ZORP $args &
			echo -n "$instance_name "
		fi

	done
}

stop() {
	egrep -w "^$1" $INSTANCES | egrep -v "^#|^$" | while read line; do
		instance_name=`echo $line | cut -d ' ' -f 1`
		if [ -r $pidfiledir/zorp-$instance_name.pid ]; then
			pid=`cat $pidfiledir/zorp-$instance_name.pid`
			if kill -TERM $pid >/dev/null 2>/dev/null; then
				echo -n "$instance_name "
			else
				echo -n "$instance_name! "
				rm $pidfiledir/zorp-$instance_name.pid
			fi
		else
			echo -n "$instance_name! "
		fi
	done
}

status() {
	egrep -w "^$1" $INSTANCES | egrep -v "^#|^$" | while read line; do
		instance_name=`echo $line | cut -d ' ' -f 1`
		echo -n "Instance $instance_name: "
		if [ -r $pidfiledir/zorp-$instance_name.pid ]; then
			pid=`cat $pidfiledir/zorp-$instance_name.pid`
			if kill -CONT $pid >/dev/null 2>/dev/null; then
				threads=`ps axu | grep "zorp --as $instance_name" | wc -l | sed -e 's/ *\([0-9]*\)$/\1/'`
				echo "running, $threads threads active."
			else
				echo "stale pidfile."
			fi
		else
			echo "not running."
		fi
	done
}


if ! egrep -v "^#|^$" $INSTANCES >/dev/null 2>/dev/null; then
	echo "You seem to have no Zorp instances configured in $INSTANCES."
	echo "For more information check out instances.conf(5)"
	exit 0
fi

x=`ls -ld $sysconfdir | cut -d ' ' -f 1`
if [ "$x" != "drwx------" ]; then
	echo "Permissions of $sysconfdir are bad. It should be 0700, fix it!"
	exit 0
fi

if [ "x$1" != "xrestart" -a "x$2" = "x" ]; then
	set "$1" ".*"
fi

case "$1" in
	start)
		shift
		echo -n "Starting Zorp Firewall Suite: "

		while [ "x$1" != "x" ]; do
			start "$@"
			shift
		done

		echo ""
		;;
	stop)
		shift
		echo -n "Stopping Zorp Firewall Suite: "

	      	while [ "x$1" != "x" ]; do
			stop "$@"
			shift
       		done
		echo ""
		;;
	restart)
		shift

	        $0 stop $@
		sleep 2
		$0 start $@
		;;
	version)
		echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
		echo "ZORP=$ZORP"
		$ZORP --version
		;;
	status)
	      	while [ "x$1" != "x" ]; do
			status "$@"
			shift
       		done
		;;
	*)
		echo "Usage: $0 start [instance] |stop [instance] |restart [instance]| status [instance] | version"
		;;
esac
