#!/bin/ash

# Copyright 2001-2004 Gentoo Technologies, Inc.
# Distributed under the terms of the GNU General Public License, v2 or later


#// Modified Functions copied from Gentoo's /sbin/functions.sh
#//--------------------------------------------------------------------------------

# void einfo(char* message)
# show an informative message (with a newline)
einfo() {
        echo -e " * ${*}"
        return 0
}

#//--------------------------------------------------------------------------------



#// Setup networking
#//--------------------------------------------------------------------------------

SetupNetwork() {

	#// DHCP or Static?
	if [ "${1}" = "dhcp" ]; then
		#// Do DHCP
		udhcpc -i eth0 -q
	else

		#// Check second param
		if [ -z "${2}" ]; then
			echo -e ""
			einfo "Please specify a gateway address."
			echo -e ""
			exit
		fi

		#// Get networking params
		BROADCAST="$(ipcalc -b ${1} | cut -d\= -f2)"
		NETMASK="$(ipcalc -m ${1} | cut -d\= -f2)"

		#// Enable static networking
		/sbin/ifconfig eth0 ${1} broadcast ${BROADCAST} netmask ${NETMASK}
		/sbin/route add -net default gw ${2} netmask 0.0.0.0 metric 1
	fi
}

#//--------------------------------------------------------------------------------



#// Launch Telnet
#//--------------------------------------------------------------------------------

#// If called, we launch telnet on port 23 and tell the user
LaunchTelnet() {
	telnetd -l /linuxrc

	#// Was it launched?
	[ ! -z "$(ps | grep "telnetd")" ] && TELNETDUP="true" || TELNETDUP="false"
}			

#//--------------------------------------------------------------------------------



#// Main Function
#//--------------------------------------------------------------------------------

#// Check first param
if [ -z "${1}" ]; then
	echo -e ""
	einfo "Please specify \"dhcp\" for setting up networking via dhcp or"
	einfo "specify an IP Address and gateway address to configure static"
	einfo "networking."
	echo -e ""
	exit
fi


#// Setup the Network
SetupNetwork ${1} ${2} ${3}


#// Was the network setup?
if [ ! -z "$(ifconfig | grep "eth0")" ]; then
	#// Get the IP
	MYIP="$(ifconfig | grep "inet addr" | cut -d":" -f2 | cut -d" " -f1 | head -n 1)"
	einfo "IP Address: ${MYIP}"
	echo -e ""


	#// Was telnet requested?
	if [ "${1}" = "dhcp" ]; then
		[ "${2}" = "telnet" ] && LaunchTelnet
	else
		[ "${3}" = "telnet" ] && LaunchTelnet
	fi


	#// Did telnet launch or not?
	if [ "${TELNETDUP}" = "true" ]; then
		einfo "Telnetd has been launched on IP ${MYIP} on Port 23"
		echo -e ""
	fi
fi

#//--------------------------------------------------------------------------------

