#!/bin/sh

prefix=${DESTDIR}/usr/pkg

# parse the args
ID=""
KILLARGS=""
LOCALSTATEDIR=${DESTDIR}/var
FIRST=1
NEXTISLOCALSTATEDIR=0
for arg in $@
do
	if ( test "$arg" = "-localstatedir" )
	then
		NEXTISLOCALSTATEDIR=1
	else
		if ( test "$NEXTISLOCALSTATEDIR" = "1" )
		then
			LOCALSTATEDIR=$arg
			NEXTISLOCALSTATEDIR=0
		elif ( test "$FIRST" = "1" )
		then
			ID=`echo $arg | sed -e "s| ||g" 2> /dev/null`
			FIRST=0
		else
			KILLARGS=$arg
		fi
	fi
done

PIDDIR=$LOCALSTATEDIR/sqlrelay/tmp/pids

FILES=""
if ( test -z "$ID" )
then
	LISTENERS="$PIDDIR/sqlr-listener-*"
	CONNECTIONS="$PIDDIR/sqlr-connection-*.*"
	SCALERS="$PIDDIR/sqlr-scaler-*"
	CACHEMANAGER="$PIDDIR/sqlr-cachemanager.*"
else
	LISTENERS="$PIDDIR/sqlr-listener-$ID"
	CONNECTIONS="$PIDDIR/sqlr-connection-$ID.*"
	SCALERS="$PIDDIR/sqlr-scaler-$ID"
	CACHEMANAGER=""
fi

for thing in $LISTENERS $CONNECTIONS $SCALERS $CACHEMANAGER
do
	if ( test -n "$thing" )
	then
		for file in `ls $thing 2> /dev/null`
		do
			if ( test -r "$file" )
			then
				PID=`cat $file`
				echo "killing process $PID..."
				kill $KILLARGS $PID
				if ( test "$?" = "0" )
				then
					echo "   success"
				else
					echo "   failed"
					rm -f $file
				fi
			fi
		done
	fi
done
