#!/bin/bash

# sqpnetapply v1.01 (13th March 2012) by Andy Davison
#  Executed by JogglerNetwork

PLATFORM=`cat /tmp/sqp_platform`
[ "$PLATFORM" = "native" ] || export PATH=$PATH:`dirname $0`

DEBUG=0

readnetsettings() {
	
	SETTINGS=`cat ~/.squeezeplay/userpath/settings/JogglerNetwork.lua`
	LOOPVAR=${SETTINGS}

	while echo $LOOPVAR | grep \, >/dev/null
	do

		LOOPTEMP=${LOOPVAR%%\,*}
		LOOPVAR=${LOOPVAR#*\,}

		VAR=`echo $LOOPTEMP | awk -F\= '{print $1}'`
		VAL=`echo $LOOPTEMP | awk -F\" '{print $2}'`

		[[ "$VAR" =~ "settings" ]] && NIC="$VAL"
		[[ "$VAR" == "ssid" ]] && SSID="$VAL"
		[[ "$VAR" == "psk" ]] && PSK="$VAL"
	
		[ $DEBUG -eq 1 ] && echo "This is the VAR = $VAR"
		[ $DEBUG -eq 1 ] && echo "This is the VAL = $VAL"

	done

	[ $DEBUG -eq 1 ] && echo
	[ $DEBUG -eq 1 ] && echo "The NIC is $NIC"
	[ $DEBUG -eq 1 ] && echo "The SSID is $SSID"
	[ $DEBUG -eq 1 ] && echo "The PSK is $PSK"
	
}

applynetsettings() {
	
	# Build the interfaces file
	echo "auto lo" > /tmp/interfaces.tmp
	echo "iface lo inet loopback" >> /tmp/interfaces.tmp
	echo >> /tmp/interfaces.tmp
	echo "auto $NIC" >> /tmp/interfaces.tmp
	echo "iface $NIC inet dhcp" >> /tmp/interfaces.tmp
	
	if [ "$NIC" == "wlan0" ]; then
		[ "$SSID" != "" ] && echo "wpa-ssid \"$SSID\"" >> /tmp/interfaces.tmp
		[ "$SSID" != "" ] && echo "wpa-psk \"$PSK\"" >> /tmp/interfaces.tmp
	fi
	
	# Overwrite the previous interfaces file
	sudo mv /tmp/interfaces.tmp /etc/network/interfaces
	sudo chown root:root /etc/network/interfaces
	
	if [[ "$NIC" == "wlan0" ]] && [[ "$PSK" != "" ]]; then
		sudo chmod 600 /etc/network/interfaces
	else
		sudo chmod 644 /etc/network/interfaces
	fi
	
}

if [ "$1" == "apply" ]; then

	readnetsettings
	sleep 1
	applynetsettings
	sleep 1
	sudo reboot
	exit 0

elif [ "$1" == "reset" ]; then
	
	rm ~/.squeezeplay/userpath/settings/JogglerNetwork.lua &>/dev/null
	NIC="eth0"
	applynetsettings
	sudo chmod 644 /etc/network/interfaces
	exit 0
	
elif [ "$1" == "ip" ]; then
	
	readnetsettings
	[[ "$NIC" =~ "wlan" ]] && INTERFACE="Wireless"
	[[ "$NIC" =~ "eth" ]] && INTERFACE="Ethernet"
	IP=`ifconfig $NIC | grep 'inet addr' | awk -F\addr: {'print $2'} | awk -F\  {'print $1'}`
	
	if [ "$IP" != "" ]; then
		echo -n "$INTERFACE interface is active. Current IP: $IP"
	else
		echo -n "No network address has been assigned to the $INTERFACE interface ($NIC)."
	fi
	exit 0
	
else

	echo "I've got nothing to do."
	exit 0
	
fi