#!/bin/bash
# console-config/src/sbin-scripts/net-setup
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Menu-based configuration for a wired ethernet device.
#

if [ "$#" -ne 1 ]
then
	echo "Expecting one argument: device to configure." >&2
	exit 1
fi

DEVICE="$1"
NETWORK_PATH="/etc/network"
DIALOG_RESULTFILE="`mktemp`"
trap "rm -f \"${DIALOG_RESULTFILE}\"" EXIT



#
# Gather information from original file
#
ORIG_FILE="${NETWORK_PATH}/${DEVICE}"
if [ ! -r "${ORIG_FILE}" ]
then
	echo "Unknown network device '${DEVICE}'!" >&2
	exit 1
fi

DESCRIPTION="`varfget "${ORIG_FILE}" desc`"
STATIC_IP="`varfget "${ORIG_FILE}" default_address_ip`"
STATIC_GATEWAY="`varfget "${ORIG_FILE}" default_route_via`"
STATIC_DNS0="`varfget "${ORIG_FILE}" default_nameserver0`"
STATIC_DNS1="`varfget "${ORIG_FILE}" default_nameserver1`"



#
# Test for how the user wants to configure the interface
#
dialog --title "Configuration for ${DEVICE}" \
	--menu \
	"Select how this interface will be configured" \
	0 0 0 \
	"DHCP" "Automatically configured by DHCP" \
	"Static" "Manually assigned static IP address" \
	"Off" "Powered off" \
	2> "${DIALOG_RESULTFILE}"
if [ "$?" -ne 0 ]
then
	clear
	echo "Cancelled."
	exit 1
fi
DIALOG_RESULT="`cat "${DIALOG_RESULTFILE}"`"




case "${DIALOG_RESULT}" in
DHCP)
	ENABLE="true"
	BOOTPROTO="dhcp"
	;;

Static)
	ENABLE="true"
	BOOTPROTO="static"

	# Gather information for a static configuration
	net-setup-static "${DEVICE}" \
		"${DIALOG_RESULTFILE}" \
		"${STATIC_IP}" \
		"${STATIC_GATEWAY}" \
		"${STATIC_DNS0}" \
		"${STATIC_DNS1}"
	if [ $? -ne 0 ]
	then
		exit 1
	fi
	{
		read -r STATIC_IP
		read -r STATIC_GATEWAY
		read -r STATIC_DNS0
		read -r STATIC_DNS1
	} < "${DIALOG_RESULTFILE}"
	;;

Off)
	ENABLE="false"
	BOOTPROTO="disabled"
	;;

*)
	echo "Unknown field '${DIALOG_RESULT}'. Bug in script!" >&2
	exit 1
esac



#
# Write out the new device file
#
clear
set -e

NEW_FILE="`mktemp ${NETWORK_PATH}/.${DEVICE}.XXXXXX`"
cat > "${NEW_FILE}" <<EOF
# Version 1 configuration file
NETCONFIG_VERSION="1"

# Interface settings
device="${DEVICE}"
desc="${DESCRIPTION}"
enable="${ENABLE}"
onboot="${ENABLE}"

# Device settings
media="Auto"
mtu=""

# DHCP settings
bootproto="${BOOTPROTO}"
dhcpcd_args=""

# static settings, first address
default_address_ip="${STATIC_IP}"
default_address_broadcast=""
default_address_args=""
default_route_via="${STATIC_GATEWAY}"
default_route_args=""
default_nameserver0="${STATIC_DNS0}"
default_nameserver1="${STATIC_DNS1}"
EOF

chgrp netconf "${NEW_FILE}"
chmod 0644 "${NEW_FILE}"
mv "${NEW_FILE}" "${ORIG_FILE}"

echo "Saved configuration file."



#
# Activate the new configuration
#
svc "net_${DEVICE}" restart
echo "Restarted network interface. Use \"ip addr\" to check address."
