#!/bin/bash
#
# $Id: safe_xvb_check_extip,v 1.1 2019/08/12 10:30:46 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 '[Cc]heck_extip.pl'`
if [ "x$PROC" != "x" ]; then
	echo "check_extip 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/check_extip.pl "daemon" "$XVB_CONFIG"
		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 CHECK_EXTIP exited on signal $EXITSIGNAL." 
			if [ "$NOTIFY" != "" ]; then
				echo "XVB CHECK_EXTIP server on $MACHINE exited on signal $EXITSIGNAL. Might want to take a peek." | \
				mail -s "XVB CHECK_EXTIP server Died" $NOTIFY
			fi
			if [ "$REG_UAC_EXEC" != "" ]; then
				$REG_UAC_EXEC
			fi
		else
			echo "XVB CHECK_EXTIP exited on signal $EXITSIGNAL." 
		fi
		echo "Automatically restarting XVB CHECK_EXTIP server." 
		date  
		sleep $SLEEPSECS
	done
}

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