#!/bin/bash
# console-config/src/sbin-scripts/net-setup
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Top-level menu for configuring network devices. If there is only one network
# device present, jumps straight into configuration of this device; otherwise,
# presents a menu allowing the user to select a device to configure. Dispatches
# result to device-specific script such as net-setup-eth etc.
#

NETWORK_PATH="/etc/network"


#
# Gather information about present devices
#
#  MENU: arguments to dialog's --menu option; has alternate <tag> <description>
#  entries where <tag> is the device name.
#
#  SCRIPT_TYPES: associative array, with device names as key and the type of the
#  next script to run as the value. The script net-setup-<VALUE> will be run if
#  the associated device is selected.
#
num_devices=0
declare -a MENU
declare -a SCRIPT_TYPES

dispatch_device() {
	local device_file="$1"
	local device="`varfget "${device_file}" device`"	
	local desc="`varfget "${device_file}" desc`"	

	if [ "${device:0:3}" == "eth" ]
	then
		SCRIPT_TYPES["${device}"]="eth"
		MENU+=("${device}")
		MENU+=("${desc}")
		((++num_devices))
	fi
}

for i in "${NETWORK_PATH}"/*
do
	[ -f "${i}" ] && dispatch_device "${i}"
done



#
# Choose device to configure
#
configure_device() {
	local device="$1"

	"net-setup-${SCRIPT_TYPES[${device}]}" "${device}"
	exit $?
}

if [ "${num_devices}" -eq 0 ]
then
	echo "No network devices detected."
	exit 1
fi

if [ "${num_devices}" -eq 1 ]
then
	# only one device present — choose it
	configure_device "${MENU[0]}"
fi

# Show selection dialog. Result will be on stderr.
DIALOG_RESULTFILE="`mktemp`"
dialog --menu \
	"Select network device to configure." \
	0 0 0 \
	"${MENU[@]}" \
	2> "${DIALOG_RESULTFILE}"
if [ $? -ne 0 ]
then
	clear
	echo "Cancelled."
	rm -f "${DIALOG_RESULTFILE}"
	exit 1
fi
clear
DIALOG_RESULT="`cat "${DIALOG_RESULTFILE}"`"
rm -f "${DIALOG_RESULTFILE}"

configure_device "${DIALOG_RESULT}"
