#!/usr/bin/env bash

## install.sh v1.00 (17th October 2023)
##  Simple installer for SqueezePlay.

### Configuration #####
SQPSERVER="https://openbeak.net/openframe/squeezeplay/v7.8"
#######################

LATESTSQP=$(curl -s $SQPSERVER/ | grep '<a' | grep '.tgz' | grep -v '.tgz.md5' | awk -F'.tgz\">' {'print $2'} | awk -F'</' {'print $1'} | tail -1)

[ -d /opt/squeezeplay ] && rm -rf /opt/squeezeplay

wget -P /tmp $SQPSERVER/$LATESTSQP
wget -P /tmp $SQPSERVER/$LATESTSQP.md5

TGZHASH=$(cat /tmp/$LATESTSQP.md5 | awk -F' ' {'print $1'})
OURHASH=$(md5sum /tmp/$LATESTSQP | awk -F' ' {'print $1'})

echo $TGZHASH
echo $OURHASH
echo

if [[ "$TGZHASH" == "" ]] || [[ "$OURHASH" == "" ]]; then

	echo "No checksums! Looks like the download failed."
	exit 1

fi

if [[ ! "$OURHASH" == "$TGZHASH" ]]; then

	echo "Checksum mismatch. Bailing!"
	rm /tmp/squeezeplay-*.tgz*
	exit 1

else

	echo "Checksums match, continuing..."

	# Create a standard user 'squeezeplay' with no configured password.
	id -u squeezeplay &>/dev/null || useradd -s /bin/sh --create-home squeezeplay
	adduser squeezeplay audio &>/dev/null
	adduser squeezeplay users &>/dev/null
	adduser squeezeplay video &>/dev/null

	# Allow squeezeplay user to do power off and reboot and stuff.
	SQPPOLKIT="polkit.addRule(function(action, subject) {
if (subject.user == "squeezeplay") {
	// permit reboot/etc actions for squeezeplay user (jive UI)
	if (action.id == "org.freedesktop.login1.power-off" ||
		action.id == "org.freedesktop.login1.reboot" ||
		action.id == "org.freedesktop.login1.set-wall-message" ||
		action.id == "org.freedesktop.login1.power-off-multiple-sessions" ||
		action.id == "org.freedesktop.login1.reboot-multiple-sessions") {
		return polkit.Result.YES;
	}
}
});"
	echo "$SQPPOLKIT" > /etc/polkit-1/rules.d/60-squeezeplay.rules
	chown root: /etc/polkit-1/rules.d/60-squeezeplay.rules

	# Install SqueezePlay with 'squeezeplay' user permissions.
	mkdir /opt/squeezeplay
	chown squeezeplay:audio /opt/squeezeplay
	sudo -u squeezeplay tar -C /opt/squeezeplay -zxf /tmp/$LATESTSQP

	# Configure the system to run SqueezePlay without requiring login.
	of-settings autostartx squeezeplay
	of-settings autoxrun squeezeplay "/opt/squeezeplay/bin/squeezeplay.sh"

	# Configure splash screens.
	if [ -d /usr/share/plymouth/themes ]; then
		mkdir /usr/share/plymouth/themes/squeezeplay
		cp /opt/squeezeplay/share/plymouth/* /usr/share/plymouth/themes/squeezeplay
		of-settings splash squeezeplay
		of-settings grubquiet enable
	fi

	# Tidy up.
	rm /tmp/squeezeplay-*.tgz*

	sync
	echo "Installation of SqueezePlay completed."

fi