#!/bin/sh
# Save NETWORK_CONFIG before sourcing so it doesn't get overridden
[ -n "$NETWORK_CONFIG" ] && NETWORK_CONFIG_ENV="$NETWORK_CONFIG"
[ -e /etc/rc.defaults ] && . /etc/rc.defaults
[ -e /etc/rc.conf ] && . /etc/rc.conf
[ -e /etc/network ] && . /etc/network

# Source a custom configuration file if specified
# in the environment.
if [ -n "$NETWORK_CONFIG_ENV" ]
then
	. "$NETWORK_CONFIG_ENV"
elif [ -n "$NETWORK_CONFIG" ]
then
	. "$NETWORK_CONFIG"
fi

case "$1" in
	start)
		ifconfig lo up

		if [ -n "$wfc_config" ]
		then
			eval `wfcdump -c $wfc_config`
			broadcast=
		fi

		if [ -n "$essid" ]
		then
			echo "Configuring wireless interface:"

			if [ -n "$channel" ]
			then 
				echo "Channel:  $channel"
				iwconfig nds channel "$channel"
				sleep 1
			else
				echo "Starting AP scan (channel detection)"
				ifconfig nds up
				sleep 1
				iwlist nds scan >/dev/null 2>/dev/null
			fi

			echo "ESSID:    $essid"
			iwconfig nds essid "$essid"
			sleep 1

			if [ -n "$wepkey" ]
			then
				echo "Setting wepkey."
				iwconfig nds key "$wepkey"
				sleep 1
			fi
		else
			echo "Not configuring network:"
			echo "No ESSID defined. See /etc/rc.defaults!"
			exit 1
		fi

		ifconfig nds down
		sleep 1

		if [ -z "$ip" ]
		then
			echo "Configuring network via DHCP."
			# We have very little RAM, so use 'exec' to avoid
			# forking a new process for the dhcp client. This is
			# the last command to run anyway if using dhcp.
			exec udhcpc -n -q -i nds
			### NOT REACHED ###
		elif [ -n "$gateway" ]
		then

			ifconfig_args=""

			echo "Configuring network:"
			echo "IP:        $ip"
			echo "Gateway:   $gateway"
			ifconfig_args="$ifconfig_args $ip"

			if [ -n "$netmask" ]
			then
				echo "Netmask:   $netmask"
				ifconfig_args="$ifconfig_args netmask $netmask"
			fi

			if [ -n "$broadcast" ]
			then
				echo "Broadcast: $broadcast"
				ifconfig_args="$ifconfig_args broadcast $broadcast"
			fi

			ifconfig nds $ifconfig_args up
			sleep 1
			route add default gw "$gateway"

			if [ -n "$dns1" ]
			then
				echo "1st DNS:   $dns1"
				echo "nameserver $dns1" > /etc/resolv.conf
				if [ -n "$dns2" ]
				then
					echo "2nd DNS:   $dns2"
					echo "nameserver $dns2" >> /etc/resolv.conf
				fi
			fi
		else
			echo "Not configuring network:"
			echo "Static configuration incomplete and DHCP is disabled."
			exit 1
		fi

		exit 0
	;;
	stop)
		echo "Stopping network."
		ifconfig lo down
		ifconfig nds down
		kill `pidof udhcpc` 2> /dev/null
	;;	
	restart)
		$0 stop
		$0 start
	;;
	*)
		echo "Usage: $0 <start|stop|restart>"
		exit 1
	;;
esac

