#!/bin/bash

# Copyright 2006 Vincent "Script.Fan(ix)" Riquer

#
# GPL preampble here
#

CONFIG="${1:-/etc/net-chooser.conf}"

if [ ! -r $CONFIG ] ; then
	echo "Could not find config file... Dying" >&2
	exit 1
fi

index_connection=0
CONNECTIONS=''

function parse_config {
	while read line ; do
		if echo "$line" | grep Name > /dev/null ; then
			index_connection=$(( $index_connection + 1 ))
			CONNECTIONS="$CONNECTIONS ${line#*=}"
		else
			CONNECTIONS="$CONNECTIONS:${line#*=}"
		fi
	done
	echo $CONNECTIONS
}

function display_menu {
	count=0
	for connection in $1 ; do
		count=$(( $count + 1 ))
		tab_connections[$count]="$connection"
		echo "$count) ${connection%%:*}" >&2
	done
	read -n ${#count} -p "Number of your setup : " >&2
	echo >&2
	if [ $REPLY -le $count ]; then
		echo ${tab_connectoins[$REPLY]}
	fi
}

function exec_choice {
	read connection
	NAME=${connection%%:*}
	connection=${connection#*:}
	IFACE=${connection%%:*}
	connection=${connection#*:}
	IP=${connection%%:*}
	connection=${connection#*:}
	if [ $IP -eq "dhcp" ] ; then
		if [ -z $DHCP ]; then
			echo "NO DHCP CLIENT SET in config file ! Check your setup !"
			exit 10
		fi
		$DHCP $IFACE && exit 0
	fi
	MASK=${connection%%:*}
	connection=${connection#*:}

	ifconfig $IFACE $IP $(if [ -n $MASK ]; then echo "mask $MASK" ; fi) || exit $(( 100 + $? ))
	
	GATEWAY=${connection%%:*}
	connection=${connection#*:}

	if [ -n $GATEWAY ]; then
		route add default gw $GATEWAY || exit $(( 200 + $? ))
	fi
	
	DNS=${connection%%:*}
	connection=${connection#*:}

	if [ -n $DNS ]; then
		SEARCH=$(grep search /etc/resolv.conf)
		echo -e "$SEARCH\nnameserver $DNS" > /etc/resolv.conf
	fi
}

DHCP=$(grep DHCP $CONFIG)
DHCP=${DHCP#*=}
if [ -z $DHCP ]; then
	echo "You didn't specify any DHCP client in the config file... This is OK if"
	echo "you use static IPs"
fi

CONNECTIONS="$(egrep -v '#|^$|DHCP' $CONFIG | parse_config)"

display_menu "$CONNECTIONS" | exec_choice
until [ $? -eq 0 ] ; do
	display_menu "$CONNECTIONS" | exec_choice
done
