#!/bin/sh

# sqp_JogglerUpdate.sh v1.09 (20th April 2012) by Andy Davison
#  Called by the JogglerUpdate applet to check for and install updates, and return changelog.

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

SERVER="http://birdslikewires.co.uk/download/joggler/squeezeplay"

if [ $# -eq 0 ] || [ $# -gt 2 ]; then
	echo "Usage: $0 <option>"
	echo
	echo "  id:            Returns this Joggler's ID (the wlan0 mac address)"
	echo "  verins:        Returns the version of SqueezePlay currently installed."
	echo "  verchk:        Checks with sever and returns the latest version number or 'NOUPDATE' if none."
	echo "  clog <ver>:    Fetches the changelog, up to the currently installed version (ver)."
	echo "  update:        Installs the latest update."
	exit 0
fi

if [ "$PLATFORM" = "native" ]; then
	INSTALL_DIR="/media/opt"
	SUDO=""
else
	INSTALL_DIR="/opt"
	SUDO="sudo"
fi

jogglerid() {
	ID=""
	if [ "$PLATFORM" = "native" ]; then
		[ "$ID" = "" ] && ID=`ifconfig | grep ra0 | awk -F\HWaddr\  {'print $2'} | tr -d ' '  | tr "[:lower:]" "[:upper:]"`
	else
		[ "$ID" = "" ] && ID=`/bin/grep wlan0 /etc/udev/rules.d/70-persistent-net.rules 2>/dev/null | awk -F\address}==\" {'print $2'} | awk -F\" {'print $1'} | tr "[:lower:]" "[:upper:]"`
		[ "$ID" = "" ] && ID=`ifconfig | grep wlan0 | awk -F\HWaddr\  {'print $2'} | tr -d ' ' | tr "[:lower:]" "[:upper:]"`
		[ "$ID" = "" ] && ID=`ifconfig | grep eth0 | awk -F\HWaddr\  {'print $2'} | tr -d ' ' | tr "[:lower:]" "[:upper:]"`
	fi
	[ "$ID" = "" ] && ID="DE:AD:BE:EF:CA:FE"
}

## Basic requests first.

# Get the Joggler ID (wireless mac address).
jogglerid
[ "$1" = "id" ] && echo -n $ID

# Get the currently installed version of SqueezePlay for Joggler...
VERINS=`/bin/sed -n 1p $INSTALL_DIR/squeezeplay/version | tr  -d \'\n\'`
[ "$1" = "verins" ] && echo -n $VERINS

# ...and the currently installed SqueezePlay binaries themselves.
SQPINS=`/bin/sed -n 2p $INSTALL_DIR/squeezeplay/version | tr  -d \'\n\'`

# Check whether there are any newer versions.
if [ "$1" = "verchk" ]; then
	if [ -f /etc/sqp_beta ]; then
		VERCHK=`/usr/bin/wget -qO- "$SERVER/update.php?sys=$PLATFORM&cli=applet&bin=$SQPINS&ver=$VERINS&id=$ID&beta=1"`
	else
		VERCHK=`/usr/bin/wget -qO- "$SERVER/update.php?sys=$PLATFORM&cli=applet&bin=$SQPINS&ver=$VERINS&id=$ID"`
	fi
	echo -n $VERCHK
fi

# Output the changelog.
if [ "$1" = "clog" ]; then
	CLOG=`/usr/bin/wget -qO- "$SERVER/update.php?clog=$2"`
	echo "$CLOG"
fi


## Now for the update section, which is also pretty basic, really. Just have to get the installer script right.

if [ $1 = "update" ]; then
	
	$SUDO wget -qO $INSTALL_DIR/sqpinstall.sh $SERVER/sqpinstall.sh
	$SUDO chmod +x $INSTALL_DIR/sqpinstall.sh
	$SUDO $INSTALL_DIR/sqpinstall.sh applet > ~/.squeezeplay/update.log
	
fi

exit 0