#! /bin/bash

test -f /etc/profile.d/grid-env.sh && . /etc/profile.d/grid-env.sh
test -f /etc/sysconfig/glite-lb && . /etc/sysconfig/glite-lb

GLITE_LOCATION=${GLITE_LOCATION:-'/usr'}
LCG_GFAL_INFOSYS=${LCG_GFAL_INFOSYS:-'lcg-bdii.cern.ch:2170'}
GLITE_LB_MSG_NETWORK=${GLITE_LB_MSG_NETWORK:-'PROD'}

CONF=/tmp/msg.$$
TEMPLATE=$1
TARGET=$2

if [ -z "$TEMPLATE" ]; then
	echo "Usage: $0 TEMPLATE [TARGET]"
	exit 1
fi
if [ -z "$TARGET" ]; then
	TARGET=$TEMPLATE
fi

# removing and resurrecting
if [ "$GLITE_LB_MSG_BROKER" = 'false' ]; then
	if [ -f "$TARGET" ]; then
		mv $TARGET $TARGET.disabled
		echo "disabled, configuration removed"
	fi
	exit 0
fi
if [ ! -s "$TEMPLATE" ]; then
	if [ -f "$TEMPLATE.disabled" ]; then
		mv $TEMPLATE.disabled $TEMPLATE
	else
		cat <<EOF >$TEMPLATE
# automatically generated by glite-lb-msg-config

[interlogd]
plugin = activemq_cpp_plugin.so

[msg]
EOF
	fi
fi

HEADER="`cat $TEMPLATE | grep -B 1000 '^\[msg\]'`"
PREFIX="`cat $TEMPLATE | grep -A 1000 '^\[msg\]' | grep prefix  | head -n -1`"

if [ "$GLITE_LB_MSG_BROKER" = 'true' -o "$GLITE_LB_MSG_BROKER" = 'auto' -o -z "$GLITE_LB_MSG_BROKER" ]; then
	GLITE_LB_MSG_BROKER="`$GLITE_LOCATION/sbin/glite-lb-msg-brokers --bdii $LCG_GFAL_INFOSYS --network $GLITE_LB_MSG_NETWORK --sort find`" || exit $?
	# bend for using in L&B configuration:
	#   1) stomp not supported
	#   2) translate openwire -> tcp, openwire+ssl -> ssl
	#   3) temporary disable the ssl
	GLITE_LB_MSG_BROKER=`echo "$GLITE_LB_MSG_BROKER" | grep -v ^stomp | sed -e 's,openwire://,tcp://,' -e 's,openwire+ssl://,ssl://,g' | grep -v ^ssl`
	GLITE_LB_MSG_BROKER=`echo $GLITE_LB_MSG_BROKER`
fi

if [ -z "$GLITE_LB_MSG_BROKER" ]; then
	exit 2
fi

[ -z "$HEADER" ] || echo "$HEADER" > $CONF
[ -z "$PREFIX" ] || echo "$PREFIX" >> $CONF
[ -z "$GLITE_LB_MSG_BROKER" ] || echo 'broker =' $GLITE_LB_MSG_BROKER >> $CONF

if [ ! -f $TARGET ]; then touch $TARGET; fi
diff -b $TARGET $CONF >/dev/null
case $? in
	0) ;;
	1) mv $CONF $TARGET; echo "new brokers '$GLITE_LB_MSG_BROKER'" ;;
	2) rm -f $CONF; exit 2 ;;
esac
rm -f $CONF
