#!/bin/sh
#
# Monkey HTTP Daemon - Banana Script
# -----------------------------------
# This script allow you to control monkey. Written by Eduardo Silva 
# ----------------------------
# Date		: 2002/09/01.
# ----------------------------
#
# Use: ./banana OPTION
#
# Options available to banana:
#
#	start	->	start monkey
#	restart	->	restart monkey
#	stop	->	stop monkey if this is running	
#	help	->	what do u think ?

PIDFILE="/root/monkey/logs/monkey.pid"
BINMONKEY="/root/monkey/bin/monkey"
CONFIGFILE="/root/monkey/conf"

for arg in $*; do
	case "$arg" in
		-*=*) optarg=`echo "$arg" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
		   *) optarg= ;;
	esac

	if  ! test -f $PIDFILE ; then
		STATUS="no"
	else
		PIDMONKEY=`cat $PIDFILE`
		if ! kill -0 $PIDMONKEY 2>/dev/null; then
			STATUS="no"
		else
			STATUS="yes"
		fi
	fi

	case "$arg" in
		start)
			if [ "$STATUS" == "yes"  ] ; then
				echo "Monkey is running... (PID=$PIDMONKEY)"
				exit 1
			fi
			if ! test -x $BINMONKEY ; then
				echo "Error: I can't run binary file"
				exit 1
			else
				if $BINMONKEY -Dc "$CONFIGFILE"  2>/dev/null ; then
					echo "Running Monkey -> OK"
					exit 0
				fi
			fi
		;;
		stop)
			if  [ "$STATUS" == "no" ]; then
				echo "Monkey is not running."
				exit 1
			fi
			kill $PIDMONKEY
			rm -rf $PIDFILE > /dev/null
			echo "Monkey stopped ($PIDMONKEY)"
			exit 0
			;;
		restart)
			if  [ "$STATUS" == "yes" ]; then
				if ! kill $PIDMONKEY  > /dev/null ; then
					killall -9 monkey
				else
					echo -n "Stopping Monkey... "
				fi
			else
				echo -n "Monkey is not running... "
			fi		
			if ! test -x $BINMONKEY ; then
				echo "Error: I can't run binary file"
				exit 1
			else
				$BINMONKEY -Dc "$CONFIGFILE" > /dev/null
				echo "Restarting -> OK"
				exit 0
			fi
			;;
		*)
			echo "Use : banana [start|stop|restart|help]"
			exit 1
		;;
	esac
done
echo "Use : banana [start|stop|restart|help]"

exit 0
