#!/bin/sh

#
# crude Trinux interactive network configuration script
#
# Matthew Franz <mfranz@cisco.com> is to blame for this
#
# 
# usage:
#
# netcfg [interface]  NOTE: interface defaults to eth0
#

if [ "$1" = "" ]
then
	face="eth0"
else
	face=$1
fi

echo "Looking for $face"

if dmesg | grep "$face" > /dev/null 2> /dev/null

then 
	ifconfig lo 127.0.0.1 up 2> /dev/null
	route add -net 127.0.0.0 netmask 255.0.0.0 lo 2> /dev/null
	echo "Bringing down $face"
	ifconfig $face down 2> /dev/null
	killall pump 2> /dev/null

	if [ -f /etc/tux/config/eth0 ]
	then
		echo "Found static network configuration."
	else
		if [ -f /etc/tux/options/dhcp ]
		then
			echo "Using DHCP to configure $face"
			prompt="y"
		else
			echo
			echo -n "Do you want to use DHCP for $face (y/n): "
			read prompt
		fi
	fi

	if [ "$prompt" != "y" ]
	then
		cd /etc/tux/config/
		savedface=`ls eth* 2> /dev/null` 

		if [ "$savedface" = "" ]
		then
			echo -n "Enter IP Address: "
			read IP
			echo -n "Netmask [255.255.255.0]: "
			read MASK
			savedface=$face
		fi
		
		for i in $savedface
		do	
			echo "Configuring $i"
			if [ "$IP" = "" ]
			then
				IP=`cut -d" " -f1 $face`
				MASK=`cut -d" " -f2 $face`
			fi
			[ "$MASK" = "" ] && MASK="255.255.255.0"
			ifconfig $face $IP netmask $MASK up
			echo "$IP $MASK" > $face
		done
		
		if [ -f gateway ]
		then
			GW=`cat gateway`		
		else	
			echo -n "Default gateway: "
			read GW
			echo $GW > /etc/tux/config/gateway
		fi
		route add default gw $GW

		if [ -f dns ]
		then
			DNS=`cat dns`
		else
			echo -n "DNS server: "
			read DNS
			echo $DNS > /etc/tux/config/dns
		fi

		echo "nameserver $DNS" > /etc/resolv.conf
	else
		pump -i $face
	fi



[ -d /etc/proc ] || mkdir /etc/proc

ifconfig $face | grep inet | cut -d":" -f2 | cut -d" " -f1 > /etc/proc/ipaddr 
nslookup `cat /etc/proc/ipaddr` | grep -v default | grep Name | cut -d":" -f2 | tr -d ' ' > /etc/proc/hostname

IPADDR=`cat /etc/proc/ipaddr`
HOSTNAME=`cat /etc/proc/hostname`


hlen=`length "$HOSTNAME"` 

if [ $hlen -lt 1 ]
then
	HOSTNAME='trinux'
fi

echo "Setting hostname: $HOSTNAME"
hostname $HOSTNAME

echo "Building /etc/hosts"
cp /etc/tux/config/hosts /etc/hosts 2> /dev/null
echo "127.0.0.1    localhost" >> /etc/hosts
echo "$IPADDR      $HOSTNAME" >> /etc/hosts
cat /etc/hosts
echo

else
	echo "Unable to find $face.  Did the kernel recognize it?"
fi

