#! /bin/sh

PATH=/sbin:/usr/sbin:$PATH
export PATH

net=0;
interface=$1;

#
# Set debug to "echo" to cause destructive commands to be displayed
# instead of executed.  Using "set -x" also helps.
#
debug=""

# Turn on tracing.
if [ "$debug" != "" ] ; then
    set -x
fi

subsh() {
    echo "You are now in a debugging subshell (you may not see a prompt)..."
    /bin/sh
    rv=`expr $? - 128 \> 0`
    if [ $rv = 1 ] ; then
	echo "Rebooting..."
	$debug /sbin/reboot
	read a
    fi
}

	
validip() {
    ret=`echo $1 | awk '
	{ split ($0,s,"."); ret=0;
	    for (i=1; i <= 4; i++)
		if (s[i] > 255) ret++;
	}
        END {print ret}'`

    return $ret
}


getip() {
    while :
    do
	echo  "${1}? ";
	read a || exit 1;
	case $a in
	    !shell)
		subsh ;;

	    *[0-9].*[0-9].*[0-9].*[0-9]/*[0-9])
		d=`dirname $a`;
		net=`basename $a`;
		validip $d ;
		if [ "$?" = "0" ]
		then
		    eval $2=\"$d\"; return 0 ;
		fi
		return 1 ;;

	    *[0-9].*[0-9].*[0-9].*[0-9])
		validip $a ;
		if [ "$?" = "0" ]
		then
		    eval $2=\"$a\"; return 0 ;
		fi
		return 1 ;;

	    "") 
		return 1 ;;
	esac
    done
}

getstring() {
    while :
    do
	 echo "${1}? ";
	 read a;
	 case "$a" in
	    "")
		return 1 ;;
	    !shell)
		subsh ;;
	    *)
	 	eval $2=\"$a\";
		break;
	esac
    done
}

mask2net() {
    IFS=".";
    set $1;
    net=0;
    while [ $# != 0 ] ; do
	case $1 in
	255)
	    incr=8 ;;
	254)
	    incr=7 ;;
	252)
	    incr=6 ;;
	248)
	    incr=5 ;;
	240)
	    incr=4 ;;
	224)
	    incr=3 ;;
	192)
	    incr=2 ;;
	128)
	    incr=1 ;;
	0)
	    incr=0 ;;
	*)
	    incr=0 ;;
	esac
	net=`expr $net + $incr`
	shift;
    done
    echo $net;
}

while :
do
    net=0
    getstring "Hostname of router" hostname || continue;
    getip "IP address of router" ipaddr || continue;
    if [ "$net" = "0" ]
    then
	getip "Netmask of router" netmask || continue;
	net="`mask2net $netmask`"
    fi
    getip "IP address of default gateway" router || continue;
    getip "IP address of nameserver" nameserver || continue;
    getstring "Default domain" domain || continue;
    getstring "Interface to configure [$interface]" tmpint;
    if [ "$tmpint" != "" ] ; then
        interface="$tmpint"
    fi
    $debug hostname $hostname;  
    $debug ifconfig $interface addr=${ipaddr}/${net} up
    $debug route add default $router
    {
	echo "search $domain"
	echo "nameserver $nameserver"
    } > /tmp/resolv.conf

    if [ "$2" != "" ]
    then
	{
	    echo "hostname=$hostname"
	    echo "domainname=$domain"
	    echo "nameserver=$nameserver"
	    echo "network_interfaces=$interface"
	    echo "ifconfig_$interface=${ipaddr}/$net"
	    echo "defaultrouter=$router"
	} > $2
    fi
    break;
done

exit 0
