#!/bin/bash

# Some constants
NETDIALOG_COPYRIGHT="Copyright 2007 Logan Lee\nReleased under GPL.\nDISCLAIMER: ABSOLUTELY NO WARRANTY"
NETDIALOG_VERSION="0.1"
NETDIALOG_CONF=/etc/netdialog.conf

network_no=$1
help="Usage: $0 <network number in the order specified in netdialog.conf>"

if [ -z "$1" ] || [ -n "$2" ]; then
    echo $help
    exit 1
fi

while read LINE; do
# get tokens
    TOKEN_1=$(echo $LINE | cut -d" " -f1)
    TOKEN_2=$(echo $LINE | cut --complement -d" " -f1)    
# if '--' is reached break out of the while loop
    if [ "$TOKEN_1" = "--" ] && [ -n "$NETWORK" ]; then
	break
    # check for '--<NETWORK NAME>' tag and match for <NETWORK NAME>
    elif [ "$TOKEN_1" != "${TOKEN_1##--}" ] && [ "$TOKEN_1" = "--Network#$network_no" ]; then
        # then we've found the match! (that is NETWORK tag)
	NETWORK="${TOKEN_1##--}$TOKEN2"
    # process the tokens if and only if NETWORK is found
    elif [ -n "$NETWORK" ]; then
	if [ "$TOKEN_1" = "IP" ]; then
	    IP=$TOKEN_2
	elif [ "$TOKEN_1" = "MASK" ]; then
	    MASK=$TOKEN_2
	elif [ "$TOKEN_1" = "GW" ]; then
	    GW=$TOKEN_2
	elif [ "$TOKEN_1" = "DNS" ]; then
	    DNS=$TOKEN_2
	elif [ "$TOKEN_1" = "ETH" ]; then
	    ETH=$TOKEN_2
	elif [ "$TOKEN_1" = "DESC" ]; then
	    DESC=$TOKEN_2
	fi
    # tag(s) for common settings
    elif [ "$TOKEN_1" = "EXEC" ]; then
	EXEC=$TOKEN_2
    fi
done < $NETDIALOG_CONF

# why don't why just print the execution command right here?
for i in $EXEC; do
    if [ "$i" = "IP" ]; then

	return+="$IP "
    elif [ "$i" = "MASK" ]; then
	return+="$MASK "
    elif [ "$i" = "GW" ]; then
	return+="$GW "
    elif [ "$i" = "DNS" ]; then
	return+="$DNS "
    elif [ "$i" = "ETH" ]; then
	return+="$ETH "
    else
	return+="$i "
    fi
done
sudo echo "" && echo -e "Trying to activate $NETWORK:\t$DESC ..."
# make sure you moved the original resolv.conf to a safe place
# what if there are more than one DNS's?
sudo chmod 666 /etc/resolv.conf && sudo echo "nameserver $DNS" > /etc/resolv.conf && sudo chmod 644 /etc/resolv.conf
#echo "Trying $return ..." && $return
while true; do
    $(echo $return | cut -d"&" -f1)
    return=$(echo $return | cut --complement -d"&" -f1)
    if [ -z "$(echo $return | grep '&')" ]; then
	$return
	break
    fi
done
# test connection
echo "Pinging gateway $GW..." && ping -c 1 $GW && echo "Pinging a foreign address..." && ping -c 1 www.uts.edu.au
exit 0


