#!/bin/bash

CONF=/usr/conf

# get pos of beroconf
if [ -x /usr/local/bin/beroconf ]; then
	BEROCONF=/usr/local/bin/beroconf
else
	BEROCONF=/usr/fallback/beroconf
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
{
        /bin/bash -c "echo x ; sleep 1 ;  echo y"  | /bin/nc localhost 54322 > /dev/null
}

case "$1" in
	start)
		# check environment
		TDMTEMP=/tmp/isgw.tdm.tmp
		TDMCONF=/usr/conf/isgw.tdm

		/usr/local/sbin/mktdmconf "$TDMTEMP"
		#check if we need to generate a new or update an existing tdmconf
		if [ ! -f "$TDMCONF" ]
		then
			diff="x"
		else
			#remove the line containing the creation date before diffing
			cat "$TDMCONF" | grep -v autogen > "$TDMTEMP".1
			cat "$TDMTEMP" | grep -v autogen > "$TDMTEMP".2
			#workaround since we have no diff
			n1=`md5sum "$TDMTEMP".1|sed 's/ .*//'`
			n2=`md5sum "$TDMTEMP".2|sed 's/ .*//'`
			if [ $n1 != $n2 ]
			then
				diff=x
			else
				diff=""
			fi
		fi
		if [ ! -z "$diff" ]
		then
			echo "Creating new $TDMCONF";
			\cp -f "$TDMTEMP" "$TDMCONF"
		fi

		if [ ! -f $CONF/isgw.conf ]
		then
			echo "isgw: not starting, missing config file!"
			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/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)
		# stop isgw
		# /sbin/start-stop-daemon -K -p $CONF/run/isgw.pid
		killall safe_isgw

                shutdown_isgw &
                sleep 3
		killall isgw
		rm -f $CONF/run/isgw.pid

		# stop netfilter rules
		ipt_stop
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}" >&2
		exit 1
		;;
esac
