#!/usr/bin/env bash

# Quick syncplay wrapper

set -x
export LC_ALL=C.utf8
INHIBITWHO=Syncplay

if [ -f "$HOME/.local/bin/_a-usrlocalbin-functions.bash" ]; then
	. $HOME/.local/bin/_a-usrlocalbin-functions.bash
elif [ -f /usr/local/bin/_a-usrlocalbin-functions.bash ]; then
	. /usr/local/bin/_a-usrlocalbin-functions.bash
else
	echo "Library _a-usrlocalbin-functions.bash not found."
	exit 1
fi

if ! hash xdg-user-dir 2> /dev/null; then
	echo "xdg-user-dir is required for my laziness"
	exit 1
fi

if [ -f "$(xdg-user-dir RUNTIME)/syncplay.$(date -I)" ]; then
	echo "Syncplay has been touched today"
else
	# If syncplay doesn't exist, get it
	if [ ! -d "$HOME/src/github.com/syncplay" ]; then
		mkdir -p ~/src/github.com/syncplay/syncplay
		git clone https://github.com/syncplay/syncplay.git ~/src/github.com/syncplay/syncplay || exit
		mkdir -p ~/src/github.com/syncplay/syncplay/venv
	else
		# In this case Syncplay does exist, let's upgrade it
		cd ~/src/github.com/syncplay/syncplay || exit
		git pull || exit
		mkdir -p venv
	fi

	# Install icon
	mkdir -vp ~/.local/share/icons/hicolor/128x128/apps/
	ln -nsfv ~/src/github.com/syncplay/syncplay/syncplay/resources/hicolor/128x128/apps/syncplay.png ~/.local/share/icons/hicolor/128x128/apps/

	# Let's ensure we have venv setup. Spellcheck complains if I won't || exit
	# every cd, which I understand to mean in failure case terminate the script.
	cd ~/src/github.com/syncplay/syncplay || exit
	python3 -m venv venv || exit
	# Switch to the venv
	. ~/src/github.com/syncplay/syncplay/venv/bin/activate

	# pip will complain if it has updates available, so it must be updated
	# and the syncplay requirements should be up-to-date too.
	pip3 install pip --upgrade
	pip3 install -r requirements.txt --upgrade
	pip3 install -r requirements_gui.txt --upgrade
	touch $(xdg-user-dir RUNTIME)/syncplay.$(date -I)
fi

# finally launch the syncplay with any flags specified
. ~/src/github.com/syncplay/syncplay/venv/bin/activate
_inhibitshutdowncmd ~/src/github.com/syncplay/syncplay/syncplayClient.py "$@"
# my syncplay launcher says this is a terminal app, so in case something goes
# wrong, let it stay open for a moment for me to see what.
echo ""
sleep 5
set +x
