#!/bin/sh
#
# Startup script for the QCG notification service
#
# chkconfig: 2345 99 01
# description: This script starts your QCG notification service
# processname: qcg-ntfd
# pidfile: /var/run/qcg/qcg-ntf/qcg-ntfd.pid

# Source function library.
. /etc/rc.d/init.d/functions

ntfd=/usr/sbin/qcg-ntfd
[ -f $ntfd ] || exit 1

RETVAL=0
INIT_WAIT=${INIT_WAIT:-3}

start() {
	status qcg-ntfd >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "qcg-ntfd is already running."
		exit 0
	fi

	# Source networking configuration.
	. /etc/sysconfig/network
	# Check that networking is up.
	[ ${NETWORKING} = "no" ] && exit 1

	if [  `cat /proc/uptime | cut -f 1 -d '.'` -lt 3600 ]; then
		echo "Detected cold start. Waiting for 20 s." 
		sleep 20
	fi

	echo -n "Starting qcg-ntfd: "
	daemon --user=qcg-ntf "$ntfd >> /var/log/qcg/qcg-ntf/qcg-ntfd.log 2>&1"
	RETVAL=$?
	for i in `seq $INIT_WAIT`; do
		if [ $RETVAL -ne 0 ]; then
			break
		fi
		sleep 1
		/sbin/pidof $ntfd > /dev/null 2>&1
		RETVAL=$?
	done
	if [ $RETVAL -eq 0 ]; then
		touch /var/lock/subsys/qcg-ntfd
		ps -AF | grep $ntfd | grep -v "QCG Notification" | grep -v grep | awk '{ print $2 }' > /var/run/qcg/qcg-ntf/qcg-ntfd.pid
		
		# Code for setting the service address for BDII 
		URLS=$(for ((i=1;;++i)) ; do
	
			LINT_OUTPUT=`/opt/qcg/dependencies/bin/xmllint --shell /etc/qcg/qcg-ntf/qcg-ntfd.xml <<-EOF 2>/dev/null
				setns sm=http://schemas.qoscosgrid.org/core/2011/04/config 
				setns xsi=http://www.w3.org/2001/XMLSchema-instance
				cd //sm:Transport/sm:Module[$i]/sm:Authentication/sm:Module[@xsi:type='sm:atc_transport_http.service']/ancestor::sm:Module
				cat sm:Host
				cat sm:Port
			EOF
			`
		
			VALID=`echo $LINT_OUTPUT | awk '/Host/ {print "TRUE"}'`
	
			if [[ -n $VALID ]]; then
				for o in $(echo $LINT_OUTPUT) ; do
					echo $o | awk -F "[><]" '/Host/{printf("http://%s:", $3)}'
					echo $o | awk -F "[><]" '/Port/{printf("%s\n", $3)}'
				done
			else
				break 
			fi
		done)
	
		for URL in $URLS; do
			echo $URL > /var/run/qcg/qcg-ntf/qcg-ntfd.addr
			
			# ASSUMPTION: Only the first interface is reported to the file
			break  
		done      
		
		success "qcg-ntfd startup"
	else
		failure "qcg-ntfd startup"
		tail -n 100 /var/log/qcg/qcg-ntf/qcg-ntfd.log
	fi
	echo
}

stop() {
	status qcg-ntfd >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "qcg-ntfd is not running."
		exit 0
	fi

	if test "x`pidof qcg-ntfd`" != x; then
		echo -n "Shutting down qcg-ntfd: "
		killproc qcg-ntfd
	fi
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/qcg-ntfd /var/run/qcg/qcg-ntf/qcg-ntfd.pid /var/run/qcg/qcg-ntf/qcg-ntfd.addr
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status qcg-ntfd
		RETVAL=$?
		;;
	restart)
		stop
		start
		;;
	reload)
		stop
		start
		;;
	condrestart)
		if test "x`/sbin/pidof qcg-ntfd`" != x; then
			stop
			start
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|restart|condrestart|status}"
		exit 1
esac

exit $RETVAL
