#!/bin/sh
cmd=$1;

sigdir=/usr/local/ss7box
sigd=ss7boost
home=$(pwd)

function stop_all()
{
	echo " "
	echo "Stopping running processes..."

	#stop $sigd
	if [ $(pidof $sigd) ]; then
		echo -n "Sending TERM signal to $sigd..."
		eval "kill -TERM $(pidof $sigd) 2>/dev/null >/dev/null"
		if [ $? -eq 0 ]; then
			echo "OK"
		else 
			echo "FAILED"
			echo -n "Sending KILL signal to $sigd..."
			eval "kill -KILL $(pidof $sigd) 2>/dev/null >/dev/null"
			if [ $? eq 0 ]; then
				echo "OK\n"
			else
				echo "Failed"
				echo "Failed to stop $sigd"
				exit 1
			fi
		fi
	else
		echo "$sigd not running..."
	fi
		
	eval "kill -KILL $(pidof $sigd) 2>/dev/null >/dev/null"

#stop sangoma media gateway
	if [ $(pidof sangoma_mgd) ]; then
		echo -n "Sending TERM signal to sangoma_mgd..."
		eval "sangoma_mgd -term 2>/dev/null >/dev/null"
		if [ $? -eq 0 ]; then
			echo "OK"
		else 
			echo "FAILED"
			echo "Failed to stop sangoma_mgd"
			exit 1
		fi
	else 
		echo "sangoma_mgd not running..."
	fi
		
	eval "kill -KILL $(pidof sangoma_mgd) 2>/dev/null >/dev/null"
}

function start_all()
{

	eval "modprobe sctp 2> /dev/null >/dev/null"

	echo " " 
	echo "Starting processes..."
	echo -n "Starting $sigd..."

	#eval "$sigdir/$sigd >>/var/log/sangoma_bri.log 2>>/var/log/sangoma_bri.log &" 
	cd $sigdir
	eval "./$sigd" 
	if [ $?	-eq 0 ]; then
		echo "OK"
	else 
		echo "Failed"
		echo "Failed to start $sigd, check /var/log/sangoma_mgd.log for errors"
		exit 1;
	fi
	sleep 5 
	if [ ! $(pidof $sigd) ]; then
		echo "$sigd failed to start"
		echo "check /var/log/messages for errors"
		exit 1;
	fi
	echo "Started $sigd Ok"
	echo

	cd $home
	echo -n "Starting sangoma_mgd..."
	eval "sangoma_mgd -bg >/dev/null 2>/dev/null" 
	if [ $? -eq 0 ]; then
		echo "OK"
	else 
		echo "Failed"
		echo "Failed to start sangoma_mgd, check /var/log/sangoma_mgd.log for errors"
		exit 1;
	fi

	sleep 3	
	if [ ! $(pidof sangoma_mgd) ]; then
		echo "sangoma_mgd failed to start"
		echo "check /var/log/sangoma_mgd.log for errors"
		exit 1;
	fi

	echo
	echo "------------------------------------" 
	echo "Sangoma SMG running.."
	echo "log file: /var/log/sangoma_mgd.log"
	echo " "
}




ulimit -n 65536

if [ "$cmd" = "start" ]; then
	if [ $(pidof $sigd) ]; then
		echo "$sigd is currently running"
		echo "exiting..."
		exit 1
	fi

	if [ $(pidof sangoma_mgd) ]; then
		echo "sangoma_mgd is currently running"
		echo "exiting..."
		exit 1
	fi

	start_all
elif [ "$cmd" = "stop" ]; then

	stop_all
elif [ "$cmd" = "restart" ]; then
	stop_all
	start_all
else 
	echo " "
	echo "Usage: smg_ctrl <options>"
	echo "	options:"
	echo " "
	echo "start	:start $sigd and sangoma media gateway"
	echo "stop 	:stop $sigd and sangoma media gateway"
	echo "restart	:restart $sigd and sangoma media gateway"
	echo " "
fi
