#!/bin/sh
# script for generating sample jobs
#
# Copyright (c) Members of the EGEE Collaboration. 2004-2010.
# See http://www.eu-egee.org/partners/ for details on the copyright holders.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
#        
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


if test ! -z "$FAKE"; then
	SUFFIX="_fake"
fi
if [ `echo $(basename $0) | grep 'glite-lb-' | wc -l` = "1" ]; then
	PREFIX=glite-lb-
fi
LOGFD=${LOGFD:-2}
BINDIR="`dirname $0`"
for dir in "`dirname $0`/../bin" "`dirname $0`/../../../bin"; do
	if [ -d "$dir" ]; then
		BINDIR="$dir"
		break;
	fi
done
LOGEV=${LOGEV:-${BINDIR}/${PREFIX}logevent}${SUFFIX}
JOB_REG=${JOB_REG:-`dirname $0`/${PREFIX}job_reg}${SUFFIX}
EDG_JOBID=
LBPROXY=
LBPROXY_STORE_SOCK=
LARGE_STRESS=

usage()
{
	echo "Usage : $0 [-x | -X store_socket_path] [-m bkserver_machine_name][-j job_id][-l size_of_random_data]" 
	exit 4
}

# read parameters
while test -n "$1"
do
	case "$1" in 
	"-m") shift; BKSERVER_HOST="$1" ;;
	"-x") LBPROXY="-x" ;;
	"-X") shift; LBPROXY="-x"; LBPROXY_STORE_SOCK="-S $1"; LBPROXY_REG="-X $1" ;;
	"-j") shift; EDG_JOBID="$1" ;;
	"-l") shift; LARGE_STRESS="-l $1" ;;
	"*") usage ;;
	esac
	shift
done

test \( -z "$BKSERVER_HOST" \) -a \( -z "$EDG_JOBID" \) && usage

if echo "$0" | grep "cream_" >/dev/null; then TYPE=-c; fi

if [ -z "$EDG_JOBID" ] 
then
	# initial sequence code & jobid (normaly returned by job_reg)
	EDG_JOBID=
	SCRIPT=`$JOB_REG $TYPE $LBPROXY_REG -m $BKSERVER_HOST -s UserInterface | tail -n 2`
	eval $SCRIPT
	test -z "$EDG_JOBID" && exit 4
	echo EDG_JOBID=$EDG_JOBID
else
	test -z "$EDG_WL_SEQUENCE" && EDG_WL_SEQUENCE="UI=000003:NS=0000000000:WM=000000:BH=0000000000:JSS=000000:LM=000000:LRMS=000000:APP=000000:LBS=000000"
fi

send_log_ev()
{
	echo $LOGEV $LBPROXY $LBPROXY_STORE_SOCK -j "$EDG_JOBID" -c "$EDG_WL_SEQUENCE" "$@" 1>&$LOGFD
	EDG_WL_SEQUENCE=`$LOGEV $LARGE_STRESS $LBPROXY $LBPROXY_STORE_SOCK -j $EDG_JOBID -c $EDG_WL_SEQUENCE "$@" 2>/dev/null`
	test $? -ne 0 -o -z "$EDG_WL_SEQUENCE" && exit 4
	true
}

