# NMX networking script

if [ ! -f /etc/network.conf ]; then
	echo "Missing /etc/network.conf file"
	echo "Exiting..."
	exit 0
fi

. /etc/network.conf

#[ "$networking" = "none" ] && exit 0;

dhcp(){
	echo "attempting DHCP..."
	udhcpc -n

	# start linklocal configuration if dhcp fails
	if [ $? != 0 ]; then
		echo "DHCP server not found." 
		echo "Resorting to linklocal autoconfiguration."
		linklocal 
	fi
}

linklocal(){
	echo "using linklocal autoconf..."
	zcip
	hostname `/etc/init.d/getip`
}

static(){
	if [ -z "$ip" ]; then 
		echo "static: IP address not present"
		exit 1
	fi

	if [ -z "$netmask" ]; then 
		echo "static: network mask not present"
		exit 1
	fi

	ifconfig eth0 $ip netmask $netmask
	hostname `/etc/init.d/getip`
}

none(){
	hostname 127.0.0.1
}
	
default_route(){
	case "$default" in
	ethernet)
		if [ "$networking" == "static" ] ; then
			if [ -z "$gateway" ] ; then 
				# This is potentially dangerous
				#route add default dev eth0
				:
			else
				route add default gw $gateway dev eth0
			fi	
		fi
	;;
	serial)
		# read serial port config
		. /etc/serial_1.conf
		
		# setup default route
		if [ "$line_discipline" == "slip" ] ; then
			route add default gw $remoteip dev sl0
		elif [ "$line_discipline" == "ppp" ] ; then
			# This step is performed in pppd 
			#route add default gw $remoteip dev ppp0
			:
		else
			echo "default: serial port networking not configured"
			exit 1
		fi
		
		# delete ethernet routes
		route del default dev eth0
	;;
	*)
		echo "default: default route not defined - ethernet assumed"
		if [ "$networking" == "static" ] ; then
			if [ -z "$gateway" ] ; then 
				# This is potentially dangerous
				#route add default dev eth0
				:
			else
				route add default gw $gateway dev eth0
			fi	
		fi
	;;
	esac
}

services(){
	# start super server
	/usr/sbin/xinetd -stayalive -reuse -pidfile /tmp/xinetd.pid

	# redirect port 8080 requests destined for ARM port 80
	/sbin/redir --lport=8080 --cport=80 --caddr=1.0.0.2 --timeout=600 &
}

case "$1" in 
	start)
		case "$networking" in 
		dhcp)
			dhcp
		;;
		linklocal)
			linklocal
		;;
		static)
			static	
		;;
		none)
			none
		;;
		*)
			echo $"Unknown networking mode"
		;;
		esac

		# setup default route
		default_route
		
		# start network services
		services
	;;
	*)
		echo $"Usage: $0 {start}"
		exit 1
esac

