#!/bin/sh
# net-start
#
# can also be run via "start net" or "start network"
#


# find which dhcp client


if [ -x /usr/sbin/dhcpcd ]
then
	DHCPCLIENT="/usr/sbin/dhcpcd"
elif [ -x /sbin/udhcpc ]
then
	DHCPCLIENT="/sbin/udhcpc"
else
	echo "No DHCP client found!"
fi

/sbin/net-stop	# bring down any interfaces and kill dhcp clients

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

probed=`dmesg | grep eth[0-9]: | cut -d: -f1`

cd /etc/tux/config/
found_faces=`ls eth*`

echo "Found configs for: $found_faces" 

# first bring up interfaces

for i in $found_faces
do
	echo -n "Configuring $i:"
		
	if grep dhcp /etc/tux/config/$i > /dev/null 2> /dev/null
	then
		DHCP="true"
		# things are really easy we just do dhcp
		echo " using DHCP"
		killall dhcpcd 2> /dev/null
		sleep 1
		if [ $DHCPCLIENT = "/usr/sbin/dhcpcd" ]
		then
			$DHCPCLIENT $i 2> /dev/null
		else
			$DHCPCLIENT -i $i 2> /dev/null
		fi
		
	else # static IP
	
 		if [ -f /etc/tux/config/$i ]
 		then
 			echo "settings found"	
			IP=`cut -d" " -f1 /etc/tux/config/$i`
			MASK=`cut -d" " -f2 /etc/tux/config/$i`
			
			if [ "$IP" ]
			then
				ifconfig $i $IP netmask $MASK up
			fi
			
		else
			echo "no settings found, skipping..."	
		fi
	fi


	if [ "$i" = "eth0" ]
	then
		ifconfig $face | grep inet | cut -d":" -f2 | cut -d" " -f1 | grep -v 127.0.0.1 > /etc/proc/ipaddr 
		ln -sf /etc/proc/ipaddr /etc/proc/$i
		nslookup `cat /etc/proc/ipaddr` | grep -v default | grep Name | cut -d":" -f2 | tr -d ' ' | tail -n 1 > /etc/proc/hostname
	fi

done

if [ "$DHCP" ]
then
	echo "Skipping DNS and gateway config"
else
	echo -n "Adding default route: "

	GW=`cat /etc/tux/config/gateway`

	echo "$GW"
	if [ "$GW" ]
	then
		route add default gw $GW
		echo "done"			
	else
		echo "failed"
	fi

	echo -n "Builing /etc/resolv.conf (DNS): "
	# need to fix this for multiple DNS servers

	DNS=`cat /etc/tux/config/dns 2>/dev/null`

	if [ "$DNS" ]
	then
		echo "nameserver $DNS" > /etc/resolv.conf
	else
		echo "failed"
	fi
fi


# update /etc/hosts and set HOSTNAME

IPADDR=`cat /etc/proc/ipaddr`

if [ -f /etc/tux/config/hostname ]
then
	HOSTNAME=`cat /etc/tux/config/hostname`
else
	HOSTNAME=`cat /etc/proc/hostname`
	hlen=`length "$HOSTNAME"` 

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

echo "Setting hostname: $HOSTNAME"
hostname $HOSTNAME

echo "Building /etc/hosts"
if [ -f /etc/tux/config/hosts ]
then
	cp /etc/tux/config/hosts /etc/hosts
fi

echo "127.0.0.1    localhost" >> /etc/hosts
echo "$IPADDR      $HOSTNAME" >> /etc/hosts

sleep 3

