#!/bin/bash
# Pt-baselayout/src/baselayout-files/all/usr/lib/upgrade/9000-netscripts.sh
# 
#  Copyright: ©2011, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
#  Recreate /etc/init.local/net_* scripts from the latest version, to get
#  any fixes that may have occurred, and migrate older network configuration
#  files to newer version.
#

# Recreate initscripts for network devices (ensures we always have the latest
# version). Not done through the standard mechanism as they have a variable in
# the script itself setting the configuration file.
instantiate() {
	src="$1"
	interface="$2"
	dest="$3"

	sed -e "s,^INTRF=.*\$,INTRF=${interface}," \
		< "/usr/share/svc_net/${src}" > "${dest}"
}

for script in /etc/init.local/net_*
do
	[ ! -r "${script}" ] && continue
	interface="$(echo $script | sed -e 's/^.*net_\([^.]*\).*$/\1/')"

	case "${script}" in
	*net_wlan*.ip)
		instantiate "wlan_cli.generic" "${interface}" "${script}"
		;;
	*net_wlan*.link)
		instantiate "wlan_link.generic" "${interface}" "${script}"
		;;
	*)
		instantiate "net.generic" "${interface}" "${script}"
		;;
	esac
done



# Upgrade really old network configurations
TMP="$(mktemp /tmp/netconfig.XXXXXX)"

for config in /etc/conf.local/ifcfg-*
do
	[ ! -f "${config}" ] && continue
	interface="$(echo ${config} | sed -e 's/.*ifcfg-//')"

	/sbin/gsl_convert_old_netconfig.sh "${config}" > "${TMP}"
	[ $? -eq 0 ] || continue
	if diff "${TMP}" "${config}" > /dev/null 2>&1
	then
	    # New file is the same as original so just delete the temp
	    rm -f "${TMP}"
	else
	    echo " * Upgrading network configuration for ${interface}"
	    mv "${TMP}" "${config}"
	fi
done

rm -f "${TMP}"



# Migrate to /etc/network
for config in /etc/conf.local/ifcfg-*
do
	[ -e "${config}" ] || continue
	interface="$(echo ${config} | sed -e 's/.*ifcfg-//')"

	chgrp -R "netconf" "${config}"
	mv "${config}" "/etc/network/${interface}"
done



# Clean baseline_fallback from wlan config if another network is defined
WPAS=/etc/network/wlan0/wpa_supplicant.conf
if [ -r $WPAS ]
then
	if grep baseline_fallback $WPAS > /dev/null 2>&1
	then
	    if [ $(grep network= $WPAS | wc -l) -gt 1 ]
	    then
		echo " * Cleaning wpa_supplicant.conf"
		/usr/sbin/wpa_supplicant_gcs --clean --config $WPAS
	    fi
	fi
fi

