#!/bin/bash

CONF=/usr/conf
BEROCONF=/usr/fallback/beroconf
LOG_DIR=/var/log

ISGW_BIN=/usr/local/bin/isgw
ISGW_PIDFILE=/var/run/isgw.pid

if [[ -f "/tmp/isgw.devmode" && -x /tmp/isgw ]]; then
	ISGW_BIN=/tmp/isgw
fi

function ipt_stop
{
	/usr/sbin/iptables -t nat -F
	echo 0 > /proc/sys/net/ipv4/ip_forward
}

function ipt_start
{
	echo 1 > /proc/sys/net/ipv4/ip_forward
	/usr/sbin/iptables -t nat -F
}


function shutdown_isgw {
        echo "shutdown" | /bin/nc -q 3 localhost 54322 > /dev/null
}


function kill_really_every_isgw {

	killall isgw
	killall -9 isgw
	# since killall -9 isgw does not always work, loop over every instance of isgw pid found by ps and kill it
	for pid in `ps aux|grep "isgw"|grep -v grep|awk '{print $1}'`; do
		PIDDIR=/proc/"$pid"
		if [ -d "$PIDDIR" ]; then
			exefile=`readlink -f "$PIDDIR"/exe`
			if [ "$exefile" = "$ISGW_BIN" ]; then
				kill -9 "$pid"
				if [ -f /tmp/dmesg.log ]; then
					echo "########## ISGWKILL: " `date ` " killed isgw with PID " $pid >> /tmp/dmesg.log
				elif [ -f /var/log/dmesg.log ]; then
					echo "########## ISGWKILL: " `date ` " killed isgw with PID " $pid >> /var/log/dmesg.log
				fi
				
			fi
		fi
	done
}

SAVEGUARD_SYS_ENABLE_FILE=/sys/class/beronet/safeguard/enabled
function safeguard_disable {
	echo 0 > $SAVEGUARD_SYS_ENABLE_FILE
}

case "$1" in
	start)
		echo "++++++++++++++++++++++++++++++++++++++++++">> ${LOG_DIR}/isgw.err
		echo "S50isgw start called: " `date`  >> ${LOG_DIR}/isgw.err
		# create isgw.tdm
		/usr/bin/env -i bash -c "/usr/local/php/makeIsgwTdmConfig.php"

		if [ ! -f $CONF/isgw.conf ]; then
			echo "isgw: not starting, missing config file." | tee -a ${LOG_DIR}/isgw.err
			exit 0
		fi
		[ -d $CONF/log ] || mkdir $CONF/log
		[ -d $CONF/run ] || mkdir $CONF/run

		# start netfilter rules
		ipt_start

		#get eth1 up (again)
		/sbin/ifconfig eth1 up

		#check isgw.tones
		if [ ! -f /usr/conf/isgw.tones -o ! -s /usr/conf/isgw.tones ] ; then
			cp /usr/local/conf/conffs/isgw.tones /usr/conf
		fi

		# start isgw
		/sbin/start-stop-daemon -S \
			-x /usr/local/sbin/safe_isgw \
			-m -p $CONF/run/isgw.pid \
			-b
		;;
	stop)
		echo "++++++++++++++++++++++++++++++++++++++++++">> ${LOG_DIR}/isgw.err
		echo "S50isgw stop called: " `date`  >> ${LOG_DIR}/isgw.err
		# disable msp safeguard here too, it's done in safe_isgw too
		safeguard_disable
		# try to stop isgw gracefully
		shutdown_isgw
		
		sleep 3
		# defeat every resistance of isgw by killing it in various ways
		kill_really_every_isgw
		killall -9 safe_isgw
		
		#safe_isgw pidfile
		rm -f $CONF/run/isgw.pid
		#real isgw pid file
		rm -f $ISGW_PIDFILE
		if [ -d /tmp/isgw.syscallmode5/ ]; then
			touch /tmp/isgw.syscallmode5/stop
		fi
		
		# stop netfilter rules
		ipt_stop
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}" >&2
		exit 1
		;;
esac
