#!/bin/sh

# SqueezePlay for Joggler Installer v1.33 (11th December 2014) by Andy Davison
#  Installs or updates SqueezePlay for Joggler.

#set -x

### Configuration Bit ###
DEBUG=0
NATIVEOSVER="26635"
LALVERSION="108"
HOST="https://birdslikewires.net/download/openframe"
BETA=0
[ -e /etc/sqpbeta ] && BETA=1
#########################


stopit() {
	
	if [ "$PLATFORM" = "native" ]; then
		if [ "$INITIATOR" = "applet" ]; then
			killall jive
			killall tango
		elif [ "$INITIATOR" = "stick" ]; then
			halt
		else
			exit 0
		fi
	elif [ "$PLATFORM" = "sqpos" ]; then
		if [ "$INITIATOR" = "applet" ]; then
			killall jive
		else
			exit 0
		fi
	else
		if [ "$INITIATOR" = "applet" ]; then
			killall jive
			/usr/bin/gnome-power-manager &
			/opt/squeezeplay/bin/togglepanel.sh show
		else
			exit 0
		fi
	fi
	
	exit 0
	
}


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 wlan | head -1 | awk -F\HWaddr\  {'print $2'} | tr -d ' ' | tr "[:lower:]" "[:upper:]"`
		[ "$ID" = "" ] && ID=`ifconfig | grep eth | head -1 | awk -F\HWaddr\  {'print $2'} | tr -d ' ' | tr "[:lower:]" "[:upper:]"`
	fi
	[ "$ID" = "" ] && ID="DE:AD:BE:EF:CA:FE"
}


## Determine our environment.

INITIATOR="$1"
THEUSER="joggler"
BASE_DIR=`echo $0 | awk -F\/sqp {'print $1'}`

if [ "$INITIATOR" = "-h" ]; then
	echo "Usage: $0 [ initiator ] [ option ]"
	exit 0
fi

if [ -f /etc/software.ver ]; then
	
	PLATFORM="native"
	OSVER=`cat /etc/software.ver | awk '{print substr($1,1,5)}'`
	if [ $OSVER -lt $NATIVEOSVER ]; then
		echo "Please ensure your Joggler is running Software Version $NATIVEOSVER or later."
		stopit
	else
		INSTALL_DIR="/media/opt"
		SQPSET_DIR="/.squeezeplay"
		ln -s /media/opt /opt 2>/dev/null
	fi
	
elif [ -f /etc/sqpos.ver ]; then
	
	PLATFORM="sqpos"
	OSVER=`cat /etc/sqpos.ver`
	if [ "$USER" != "root" ]; then
		echo "This script needs to be run with superuser privileges."
		stopit
	fi
	INSTALL_DIR="/opt"
	SQPSET_DIR="/home/joggler/.squeezeplay"
	
else
	
	PLATFORM=`lsb_release -sc`
	OSVER=""
	if [ "$USER" != "root" ]; then
		echo "This script needs to be run with superuser privileges."
		stopit
	fi
	INSTALL_DIR="/opt"
	if [ -d /home/joggler ]; then
		SQPSET_DIR="/home/joggler/.squeezeplay"
	else
		echo "There is no 'joggler' user on your system, so I'm guessing that this is a custom OS."
		echo "I'll put the files in the right place, but autostarting and menu entries are down to you."
		echo 
		THEUSER=""
		SQPSET_DIR=""
	fi

fi

# Get the Joggler ID (wireless mac address).
jogglerid
if [ "$ID" = "" ]; then
	echo "There's been a problem grabbing this Joggler's ID."
	exit 0
fi

# Check whether we have a version already installed.
if [ -f $INSTALL_DIR/squeezeplay/version ]; then
	VERINS=`sed -n 1p $INSTALL_DIR/squeezeplay/version`
else
	VERINS=100-1.0.0-1000
fi
INSVER=`echo $VERINS | awk '{print substr($1,1,3)}'`
INSREV=`echo $VERINS | awk '{print substr($1,11,14)}'`
INSBIN=`echo $VERINS | awk '{print substr($1,5,5)}'`

# Do we have the installation files locally?
if [ -d $BASE_DIR/sqpinstall ]; then
	# Check for the files and grab version numbers.
	ONLINE=0
	UPDVER=`ls $BASE_DIR/sqpinstall/ | grep joggler-v | awk -F\-v {'print $2'} | awk -F\.tgz {'print $1'}`
	UPDBIN=`ls $BASE_DIR/sqpinstall/ | grep thinned- | awk -F\d- {'print $2'} | awk -F\.tgz {'print $1'}`
	UPDREV=`echo $UPDBIN | awk '{print substr($1,7,10)}' `
	UPDBIN=`echo $UPDBIN | awk '{print substr($1,1,5)}' `
	VERUPD="$UPDVER-$UPDBIN-$UPDREV"
	CLEANUPD=1
else
	# If they're not local, we go online and grab them.
	ONLINE=1
	if [ $BETA = 1 ]; then
		VERUPD=`/usr/bin/wget -qO- "$HOST/squeezeplay/update.php?sys=$PLATFORM$OSVER&cli=installer&ver=$VERINS&id=$ID&beta=1"`
	else
		VERUPD=`/usr/bin/wget -qO- "$HOST/squeezeplay/update.php?sys=$PLATFORM$OSVER&cli=installer&ver=$VERINS&id=$ID"`
	fi
	if [ "$VERUPD" = "NOUPDATE" ]; then
		UPDVER=999
		UPDREV=99999
		UPDBIN="9.9.9"
	else
		UPDVER=`echo $VERUPD | awk '{print substr($1,1,3)}'`
		UPDREV=`echo $VERUPD | awk '{print substr($1,11,14)}'`
		UPDBIN=`echo $VERUPD | awk '{print substr($1,5,5)}'`
	fi
fi

# A bit of version variable mangling.
MAJVER=${UPDVER%??}
MINVER=${UPDVER#$MAJVER}

# If this is an online installation, decide what we need to grab.
if [ $ONLINE = 1 ]; then

	if [ "$VERUPD" = "NOUPDATE" ]; then

		UPTODATE=1

		# Make sure we stop after spitting out the debug info.
		echo "SqueezePlay for Joggler is already the most recent version."

	else

		UPTODATE=0

		# Do we need to clear everything out? By default, no.
		CLEANUPD=0

		# If the binary revision numbers don't match we clear out and start again.
		#  This could be handled better. But it isn't.
		if [ $INSREV -ne $UPDREV ]; then
			CLEANUPD=1
		else
			CLEANUPD=0
		fi

		# Version Specific Changes

		# 140 - We clear out any version before 1.40 because this installer wasn't used before then.
		[ $INSVER -lt 140 ] && CLEANUPD=1

		# 159 - Bin the JogglerUpdateModel applet. The world wasn't ready.
		[ $INSVER -eq 159 ] && rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdateModel &>/dev/null
		
	fi
	
fi
	
if [ $DEBUG = 1 ]; then
	echo "System Variables:"
	echo "ID       =    $ID"
	echo "PLATFORM =    $PLATFORM"
	echo "INSTALL_DIR = $INSTALL_DIR"
	echo "BASE_DIR    = $BASE_DIR"
	echo
	echo "Install Variables:"
	echo "VERINS  =     $VERINS"
	echo "INSVER  =     $INSVER"
	echo "INSREV  =     $INSREV"
	echo "INSBIN  =     $INSBIN"
	echo
	echo "Update Variables:"
	echo "VERUPD  =     $VERUPD"
	echo "UPDVER  =     $UPDVER"
	echo "UPDREV  =     $UPDREV"
	echo "UPDBIN  =     $UPDBIN"
	echo
	echo "Action Variables:"
	echo "CLEANUPD  =     $CLEANUPD"
	echo "ONLINE    =     $ONLINE"
fi

[ $UPTODATE = 1 ] && stopit


## Start the installation process.

echo
echo "                           SqueezePlay for Joggler v$MAJVER.$MINVER ($UPDBIN-$UPDREV)"
echo "====================================================================="
echo "                                                 birdslikewires.co.uk"
echo
echo
echo "WARNING! It is entirely possible that this script could cause your"
echo "         Joggler to stop working, as it modifies essential system"
echo "         files. Every care has been taken to avoid this happening,"
echo "         but you must only continue if you accept this risk."
echo
echo "         No responsibility will be accepted for any damage and this"
echo "         software is provided without warranty."
echo
echo
echo "If you find SqueezePlay for Joggler useful, you might like to make"
echo "a contribution towards it's hosting and development. For information,"
echo "please visit: http://birdslikewires.co.uk/about/donate"
echo "                                                              Thanks!"
echo

if [ "$INITIATOR" = "applet" ] || [ "$INITIATOR" = "auto" ] || [ "$INITIATOR" = "stick" ]; then
	
	sleep 6
	
else
	
	[ $BETA = 1 ] && BETAMSG=" a beta version"
	
	echo
	echo "I'm about to install$BETAMSG onto a $PLATFORM system."
	echo
	echo "Press <ENTER> to continue or CTRL-C to exit."
	read RESPONSE

fi


## Prepare the systems.

[ ! -d $INSTALL_DIR ] && mkdir -p $INSTALL_DIR

# Prepare the Joggler's native operating system.
if [ "$PLATFORM" = "native" ]; then
	
	# Check for the logging dir. It's not always there for some reason.
	[ -d /media/logs ] || mkdir /media/logs

	# Check for the AppShop. I know, it should be there if people are installing on the right OS version, but just in case.
	if [ ! -d /media/appshop ]; then
		mkdir /media/appshop
		echo -e "<applications>\n</applications>" > /media/appshop/applications.xml
	fi
	
	# Install, or update, the Little App Launcher.
	if [ $ONLINE = 0 ]; then
		[ -f /media/launcher/version ] && LALINSVER=`cat /media/launcher/version`
		[ $LALINSVER -le $LALVERSION ] && tar zxf $BASE_DIR/sqpinstall/launcher$LALVERSION.tgz -C /media
		[ -f /media/launcher/version ] || echo $LALVERSION > /media/launcher/version
		/media/launcher/index.cgi >/dev/null
	else
		wget -q -O /media/launcherInstall.sh $HOST/native/launcher/launcherInstall.sh
		chmod +x /media/launcherInstall.sh
		cd /media; ./launcherInstall.sh
	fi

# Prepare SqueezePlay OS.
elif [ "$PLATFORM" = "sqpos" ]; then
	
	# If there's a .bash_profile our .profile won't be run. So delete it.
	[ -f /home/joggler/.bash_profile ] && rm /home/joggler/.bash_profile

# Prepare an Ubuntu-based system.
else
	
	echo
	echo "Preparing for SqueezePlay installation..."
	echo
	
	apt-get -y install i2c-tools wget xdotool x11-xserver-utils
	
	# Make sure users have access to alter backlight settings and read from the I2C bus.
	[ -f /etc/udev/rules.d/70-backlight.rules ] || echo 'KERNEL=="openframe-bl", RUN+="/bin/chmod 666 /sys/class/backlight/openframe-bl/bl_power /sys/class/backlight/openframe-bl/brightness"' > /etc/udev/rules.d/70-backlight.rules
	[ -f /etc/udev/rules.d/70-i2c.rules ] || echo 'KERNEL=="i2c-[0-9]*", MODE="0666"' > /etc/udev/rules.d/70-i2c.rules
	
	I2CENABLE=`cat /etc/modules`
	
	if [ ! `echo "$I2CENABLE" | grep "i2c"` ]; then
		echo i2c-dev >> /etc/modules
		modprobe i2c-dev
	fi
	
	echo " done."
	
fi


## Install!

echo
echo "Installing SqueezePlay..."
echo

# Magic up some tarballs.
if [ $ONLINE = 0 ]; then
	
	# If the files are local, just copy them to the right place.
	echo "Copying SqueezePlay for Joggler v$MAJVER.$MINVER..."
	cp $BASE_DIR/sqpinstall/squeezeplay-joggler-v$UPDVER.tgz $INSTALL_DIR/squeezeplay-joggler-v$UPDVER.tgz
	echo "Copying SqueezePlay $UPDBIN-$UPDREV binaries..."
	cp $BASE_DIR/sqpinstall/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz $INSTALL_DIR/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz
	if [ "$PLATFORM" = "native" ]; then
		echo "Copying the launcher component..."
		cp $BASE_DIR/sqpinstall/squeezeplay-launcher.tgz /media/squeezeplay-launcher.tgz
	fi
	
elif [ $ONLINE = 1 ]; then

	# We always want to grab the new tarball.
	echo "Fetching SqueezePlay for Joggler v$MAJVER.$MINVER..."
	echo
	wget -O $INSTALL_DIR/squeezeplay-joggler-v$UPDVER.tgz $HOST/squeezeplay/squeezeplay-joggler-v$UPDVER.tgz
	echo

	# If the binaries have changed, then grab those as well.
	if [ $CLEANUPD = 1 ]; then
		echo "Fetching SqueezePlay $UPDBIN-$UPDREV binaries..."
		echo
		wget -O $INSTALL_DIR/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz $HOST/squeezeplay/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz
		echo
	else
		echo "Binaries are already the latest version. No need to fetch."
		echo
	fi

	# Always grab the launch component for the native platform, just in case. 
	if [ "$PLATFORM" = "native" ]; then
		echo "Fetching the launcher component..."
		echo
		wget -O /media/squeezeplay-launcher.tgz $HOST/squeezeplay/squeezeplay-launcher.tgz
		echo
	fi

fi

# If the binaries have been updated, delete everything.
# I may change this in future if people complain about reinstalling applets, but it ensures a clean system.
if [ $CLEANUPD = 1 ] || [ "$2" = "clean" ]; then
	if [ -d $INSTALL_DIR/squeezeplay ]; then
		echo
		echo -n "Clearing out..."
		[ $DEBUG = 0 ] && rm -rf $INSTALL_DIR/squeezeplay
		echo " done."
		echo
	fi
fi

# Decompress into the correct location.
echo -n "Decompressing..."
[ $DEBUG = 0 ] && [ -f $INSTALL_DIR/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz ] && tar zxf $INSTALL_DIR/squeezeplay-thinned-$UPDBIN-$UPDREV.tgz -C $INSTALL_DIR
[ $DEBUG = 0 ] && [ -f $INSTALL_DIR/squeezeplay-joggler-v$UPDVER.tgz ] && tar zxf $INSTALL_DIR/squeezeplay-joggler-v$UPDVER.tgz -C $INSTALL_DIR
[ $DEBUG = 0 ] && rm $INSTALL_DIR/squeezeplay-*.tgz
echo " done."

# Create the version file.
echo "$UPDVER-$UPDBIN-$UPDREV" > $INSTALL_DIR/squeezeplay/version

# Set the /etc/asound.conf file to something that SqueezePlay will work with. Backup the existing one first though.
[ -f /etc/asound.conf_presqp ] || mv /etc/asound.conf /etc/asound.conf_presqp 2>/dev/null
cp $INSTALL_DIR/squeezeplay/config/asound.conf_dmix /etc/asound.conf



## Finishing up.


# Tidy up on the native platform.
if [ "$PLATFORM" = "native" ]; then


	# Remove the SqueezePlay OS config files.
	rm -rf $INSTALL_DIR/squeezeplay/config/sqpos

	# Remove the JogglerFeatures applet (this is just for sqpOS).
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerFeatures
	rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerFeatures.sh
	
	# Remove the JogglerNetwork applet (underlying OS deals with this).
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerNetwork
	rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerNetwork.sh

	# Remove the JogglerPower applet (underlying OS deals with this), but leave the script as it's used by Quit.
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerPower

	# Remove the JogglerSetupTZ applet (underlying OS deals with this).
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerSetupTZ
	rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerSetupTZ.sh

	# Apply the correct strings.txt for JogglerUpdate applet.
	cp $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt_$PLATFORM $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt
	rm $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt_*

	# Install the launcher for Little App Launcher.
	tar zxf /media/squeezeplay-launcher.tgz -C /media/launcher/apps
	rm /media/squeezeplay-launcher.tgz
	/media/launcher/index.cgi
	echo
	echo "System will restart shortly..."
	sleep 3
	reboot


# Tidy up on the SqueezePlay OS.
elif [ "$PLATFORM" = "sqpos" ]; then
	
	
	# Make sure the system logs in automatically as the joggler user.
	[ -f /etc/init/tty1.conf ] && mv /etc/init/tty1.conf /etc/init/tty1.conf_old
	cp $INSTALL_DIR/squeezeplay/config/sqpos/etc/init/tty1.conf /etc/init/tty1.conf
	
	# Make sure the profile knows to start the X server.
	[ -f /home/joggler/.profile ] && mv /home/joggler/.profile /home/joggler/.profile_old
	cp $INSTALL_DIR/squeezeplay/config/sqpos/home/joggler/sqp.profile /home/joggler/.profile
	chown joggler:joggler /home/joggler/.profile

	# Tell the X server to fire up SqueezePlay.
	[ -f /home/joggler/.xinitrc ] && mv /home/joggler/.xinitrc /home/joggler/.xinitrc_old
	cp $INSTALL_DIR/squeezeplay/config/sqpos/home/joggler/sqp.xinitrc /home/joggler/.xinitrc
	chown joggler:joggler /home/joggler/.xinitrc
	
	# Change the message-of-the-day login text.
	cp $INSTALL_DIR/squeezeplay/config/sqpos/etc/update-motd.d/* /etc/update-motd.d/
	
	# Remove the Quit applet so that we use the JogglerPower applet instead.
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/Quit
	
	# Remove the JogglerPurge applet. Not much point removing SqueezePlay from SqueezePlay OS.
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerPurge

	# Apply the correct strings.txt for JogglerUpdate applet.
	cp $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt_$PLATFORM $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt
	rm $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerUpdate/strings.txt_*
	
	# Just to be sure about permissions...
	chown -R joggler:joggler $INSTALL_DIR/squeezeplay
	
	# If we're running a version older than v1.09, we need to correct the apt sources list.
	[ "$OSVER" -lt "109" ] && sed -i 's/http:\/\/uk.archive.ubuntu.com\/ubuntu\//http:\/\/old-releases.ubuntu.com\/ubuntu/g' /etc/apt/sources.list.d/joggler.list

	# If we're on a v2 branch, there are few extra things to do.
	if [ "$OSVER" -gt "200" ]; then

		## During configuration 'loglevel=1' should have been set in /boot/grub.cfg.

		# Install the Plymouth splash screen.
		cp -R $INSTALL_DIR/squeezeplay/config/sqpos/lib/plymouth/themes/squeezeplay /lib/plymouth/themes/
		chown -R root:root /lib/plymouth/themes/squeezeplay
		update-alternatives --install /lib/plymouth/themes/default.plymouth default.plymouth /lib/plymouth/themes/squeezeplay/squeezeplay.plymouth 100
		update-alternatives --config default.plymouth
		update-initramfs -u

		# Remove the MOTD components.
		rm /etc/update-motd.d/*

		# Remove the SSH packages as they are not required.
		rm -rf $INSTALL_DIR/squeezeplay/config/sqpos/packages/ssh

	fi
	

# Tidy up on a generic Ubuntu-based platform.
else
	
	
	# Disable Pulse Audio :(
	mv /usr/share/alsa/alsa.conf.d/pulse.conf /usr/share/alsa/alsa.conf.d/pulse.conf.off
	
	# Remove the SqueezePlay OS config files.
	rm -rf $INSTALL_DIR/squeezeplay/config/sqpos
	
	# Remove the JogglerFeatures applet (this is just for sqpOS).
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerFeatures
	rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerFeatures.sh
	
	# Comment out the pulse.conf line from /usr/share/alsa/alsa.conf
	#  If anyone has any knowledge as to why this has become necessary again, your expertise would be much appreciated!
	PULSEKILL=`grep pulse.conf /usr/share/alsa/alsa.conf | grep '#'`
	[ "$PULSEKILL" = "" ] && sed -i '/\"\/usr\/share\/alsa\/pulse.conf\"/s!^!#!' /usr/share/alsa/alsa.conf
	
	# Make sure the system's own libraries are used here, as they're likely to be more up-to-date.
	rm -rf $INSTALL_DIR/squeezeplay/lib/libjpeg.so.62 $INSTALL_DIR/squeezeplay/lib/libpng12.so.0
	
	# Remove the JogglerNetwork applet (underlying OS deals with this).
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerNetwork
	rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerNetwork.sh
	
	# Remove the JogglerPower applet (underlying OS deals with this), but leave the script as it's used by Quit.
	rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerPower
	
	# Remove the JogglerPurge applet if this has been installed on a custom OS.
	if [ "$THEUSER" = "" ]; then
		rm -rf $INSTALL_DIR/squeezeplay/share/jive/applets/JogglerPurge
		rm $INSTALL_DIR/squeezeplay/bin/sqp_JogglerPurge.sh
	fi
	
	# Add the menu entry.
	if [ `which xdg-desktop-menu` != "" ]; then
		echo -n "Adding menu entry..."
		xdg-desktop-menu install --novendor --mode system $INSTALL_DIR/squeezeplay/config/squeezeplay.desktop
		echo " done."
		echo
	else
		echo "This script doesn't know how to install a menu entry for you."
	fi
	
	# If we're not running on a custom system (ie. you're using one of BuZz's builds)...
	if [ "$THEUSER" != "" ]; then
		
		# Add an autostart script if requested.
		echo -n "Would you like to launch SqueezePlay automatically? (y/n) "
		read AUTOSTART
		if [ "$AUTOSTART" = "y" ] || [ "$AUTOSTART" = "Y" ]; then
			[ ! -d /home/$THEUSER/.config/autostart ] && mkdir -p /home/$THEUSER/.config/autostart
			cp $INSTALL_DIR/squeezeplay/config/sqpautostart.sh.desktop /home/$THEUSER/.config/autostart/
			echo "The autostart will only become active after SqueezePlay has been successfully configured."
		fi
		
		# Just to be sure about permissions...
		chown -R joggler:joggler $INSTALL_DIR/squeezeplay
		
	fi

	# Make sure the log file exists and is writable.
	touch /var/log/squeezeplay.log
	chmod 666 /var/log/squeezeplay.log
	
fi

rm -rf $INSTALL_DIR/sqp*.sh
rm -rf $INSTALL_DIR/squeezeplay-*.tgz
#rm $0
sync
	
echo
echo "SqueezePlay for Joggler installation is complete."
echo

stopit
