#!/bin/sh --

. /usr/local/src/kqml/bin/kqmlenv.sh

CompareHost()
{
	# We are checking just the hostname, ignoring the domain name.

	host1=`echo $1 | tr '[a-z]' '[A-Z]' | cut -d'.' -f1`
	host2=`echo $2 | tr '[a-z]' '[A-Z]' | cut -d'.' -f1`

	if [ "$host1" = "$host2" ]
	then
		return 0
	else
		return 1
	fi
}

	
# Get the current host's name
THIS_HOST=`hostname`
if [ "$THIS_HOST" = "" ]
then
	echo "Could not find hostname."
	exit 1
fi

# Get the absolute name of the program
PROG=`echo $0 | cut -c1`
if [ "$PROG" = "/" ]
then
	PROG=$0
else
	PROG="`pwd`/$0"
fi

LOG_DIR=${KQML_DBG:-/tmp}
REMOTE=""

# Read command line options
while getopts a:l:p:r opt
do
	case $opt in
	a)
		KQML_ANS=$OPTARG
		;;
	l)
		LOG_DIR=$OPTARG
		;;
	p)
		KQML_PARENT_ANS=$OPTARG
		;;
	r)
		REMOTE="-r"
	esac
done

shift `expr $OPTIND - 1`
if [ $# -ne 1 ]
then
	echo \
		"Usage: $0 [-r] [-p <PARENT_ANS>] [-a <ADDR>] [-l <LOG_DIR>] <ANS_NAME>"
	exit 1
fi
ANS_NAME=$1

unset KQML_USE_MEDIATOR
umask 007

HOST=`echo "$KQML_ANS" | cut -d':' -f1`
if CompareHost $THIS_HOST $HOST
then
	:
else
	exec rsh $HOST -n $PROG $REMOTE -l $LOG_DIR \
		${PARENT_ANS:+"-p $PARENT_ANS"} ${KQML_ANS:+"-a $KQML_ANS"} $ANS_NAME
fi

anscheck
case $? in
0)
	echo "Another ANS is running in $HOST" >&2
	exit 1
	;;
1)
	;;
*)
	echo "Another ANS may be running in $HOST" >&2
	exit 1
esac

# We do not depend on KQML_DBG. It may not be set. Instead we 
# assume that there will be a directory called $LOG_DIR
if [ -d $LOG_DIR -a -w $LOG_DIR ]
then

	/bin/rm -f $LOG_DIR/$ANS_NAME.log > /dev/null 2>&1
	> $LOG_DIR/$ANS_NAME.log
	chmod a+r $LOG_DIR/$ANS_NAME.log

	nohup ans $REMOTE $ANS_NAME >> $LOG_DIR/$ANS_NAME.log 2>&1 &

	echo
	echo "Facilitator started"
	exit 0
else
	echo "Not enough permissions for $LOG_DIR" >&2
	exit 1
fi
