#!/bin/bash
#
# $Id: safe_xvb_agi,v 1.6 2012-02-09 15:06:23 gosha Exp $
#
# vim:textwidth=80:tabstop=4:shiftwidth=4:smartindent:autoindent

RC_CONFIG=${1-"/opt/VirtualPBX/etc/xvb-rc.cfg"}
. ${RC_CONFIG}

# Check if is already running.
PROC=`ps ax | grep '[fF]agi.pl'`
if [ "x$PROC" != "x" ]; then
	echo "Fagi is already running."
	exit 1
fi

#
# Don't die if stdout/stderr can't be written to
#
trap '' PIPE

run_xvb()
{
	while :; do 
		cd /tmp
		/opt/VirtualPBX/contrib/utils/Fagi.pl fagi "$XVB_CONFIG" "$FAGI_CHILDS" 0 "$FAGI_HOST" "$FAGI_PORT"
		EXITSTATUS=$?
		echo "ended with exit status $EXITSTATUS"
		if [ "$EXITSTATUS" = "0" ]; then
			# Properly shutdown....
			echo "shutdown normally."
			exit 0
		elif [ $EXITSTATUS -gt 128 ]; then
			EXITSIGNAL=EXITSTATUS-128
			echo "XVB exited on signal $EXITSIGNAL."
			if [ "$NOTIFY" != "" ]; then
				echo "XVB AGI server on $MACHINE exited on signal $EXITSIGNAL.  Might want to take a peek." | \
				mail -s "XVB AGI server Died" $NOTIFY
			fi
			if [ "$FAGI_EXEC" != "" ]; then
				$FAGI_EXEC
			fi
		else
			echo "XVB exited on signal $EXITSIGNAL."
		fi
		echo "Automatically restarting XVB AGI server."
		date
		sleep $SLEEPSECS
	done
}

run_xvb 2>>/var/log/VirtualPBX/XVB.stderr 1>&2 &
