#!/bin/bash
# console-config/src/sbin-scripts/net-repair
# 
#  Copyright: ©2014, Güralp Systems Ltd.
#  Author: Kelly Dunlop <kdunlop@guralp.com>
#  License: GPLv3
#
#  Network repair script to put together a basic default network config based
#  on hardware.
#

NETWORK_DIR="/etc/network.local"
NETWORK_SYMLINK="/etc/network"
DIALOG_RESULTFILE="`mktemp`"
GSL_WIRELESS_SETUP_SCRIPT="/lib/udev/gsl_wlan_setup.sh"



# Check we are running as root and confirm the user really wants to do this.
uid="`id -u`"

if [ $uid -ne 0 ]
then
	echo "net-repair needs to be run as root.  Please login as root to use it."
	exit 1
fi


dialog --defaultno \
	--yesno "Running net-repair will destroy your current network config. \
Are you sure you wish to continue ?" \
	0 0 2> ${DIALOG_RESULTFILE}

if [ $? -ne 0 ]
then
	clear
	echo "Cancelled."
	rm -f "${DIALOG_RESULTFILE}"
	exit 1
fi

# First fix the wired config files.
# Remove the /etc/network and /etc/network.local files unconditionally (they may
# exist but be incorrect. 
rm -fr "${NETWORK_DIR}"
mkdir "${NETWORK_DIR}"
echo "Created ${NETWORK_DIR} directory."

rm -fr ${NETWORK_SYMLINK}
ln -s ${NETWORK_DIR} ${NETWORK_SYMLINK}
echo "Created ${NETWORK_SYMLINK} file."

list=`ip link | grep -v ether | grep eth | cut -d " " -f 2 | sed -e "s/://"`

first=1
for device in ${list}
do
	if [ $first -eq 1 ]
	then
		desc="Primary wired network interface"
		first=0
	else
		desc="Secondary wired network interface"
	fi
	CONFIG_FILE="${NETWORK_DIR}/${device}"

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

# Interface settings
device="$device"
desc="${desc}"
enable="true"
onboot="true"

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

# DHCP settings
bootproto="dhcp"
dhcpcd_args=""

# static settings, first address
default_address_ip=""
default_address_broadcast=""
default_address_args=""
default_route_via=""
default_route_args=""
default_nameserver0=""
default_nameserver1=""
EOF

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

	echo "Saved wired configuration file ${CONFIG_FILE}."
done


# Now create the wireless config files using /lib/udev/gsl_wlan_setup.sh.
list=`ip link | grep wlan | cut -d " " -f 2 | sed -e "s/://"`

export ACTION=add

for device in ${list}
do
	export INTERFACE=${device}

	${GSL_WIRELESS_SETUP_SCRIPT}

	echo "Created files for wireless interface $device."
done

# Now clean out any potentially incorrect init scripts
rm -f /etc/init.local/net*

echo
echo "To action these changes a reboot is required."

exit 0
