#!/bin/ash
#
# This script opens up the firewall and starts the gdbserver.

. /usr/local/bin/sig_catcher


IPTABLES="/sbin/iptables"

display_usage() {
	cat << USAGE_HERE
Usage: start_gdbserver -a <application> [<port-number>]
       or
       start_gdbserver -p <proc-id> [<port-number>]
       If <port-number> is not provided, port 6466 will be used.
       If a port number is in use, the next 5 port numbers will be checked for availability.
       If a port is specified as a parameter, only that port is checked for availability.
USAGE_HERE
	exit 1
}

if [ $# -lt 2 ]
then
	display_usage
elif [ "$1" != "-a" ] && [ "$1" != "-p" ]
then
	display_usage
else

	if [ $# -lt 3 ]
	then 
		port=6466
	
		first_port=$port

		#If port is in use, try the next number up to 5 times
		loop=5;
		found="a"; #init non null value
		output=$(netstat -ltun)
		while [ $loop -ne 0 ] && [ "$found" != "" ]
		do
			found=$(echo $output | grep ":$port")
			if [ "$found" != "" ]
			then
				echo "Port $port is in use"
				port=$(($port+1))
			else
				echo "Found available port $port"
			fi

			loop=$((loop-1))
		done

		if [ $loop == 0 ] && [ "$found" != "" ]
		then
			echo "Port $first_port to $((port-1)) are not available.  Try again with a different port number."
			exit 1
		fi
	else
		port=$3
	fi

	#open firewall
	$IPTABLES -F
	$IPTABLES -P INPUT ACCEPT
	$IPTABLES -P OUTPUT ACCEPT

	IP=$(/usr/local/bin/ipaddr.sh)
	echo "The target IP address is $IP"

	if [ "$1" == "-a" ]
	then
		echo "Start gdbserver for port number $port and application $2"
		#host is ignored by gdbserver
		/usr/local/bin/gdbserver host:$port $2 &
	elif [ "$1" == "-p" ]
	then
		echo "Start gdbserver for port number $port and proc-id $2"
		#host is ignored by gdbserver
		/usr/local/bin/gdbserver host:$port --attach $2 &
	fi
fi

exit 0
