#! /bin/bash

MUZLAB_REPO="/etc/apt/sources.list.d/muzlab.list";
REPO_LIST="sources.list.d/muzlab.list";

echo "Checking if repository is installed..";

if test -f "${MUZLAB_REPO}"; then
  echo "Repository already added, skipping..";
else
  echo "Repository not available, adding..";
  wget http://deb-repo.muzlab.ru/keyring.gpg -O /etc/apt/trusted.gpg.d/muzlab.gpg;
  echo 'deb http://deb-repo.muzlab.ru focal main' > ${MUZLAB_REPO};
  echo "muzlab-client-desktop hold" | dpkg --set-selections;
  apt update -o Dir::Etc::sourcelist="${REPO_LIST}" -o Dir::Etc::sourceparts="-" -o APT::Get::List-Cleanup="0" || true
  apt install -y curl;
fi

REQ_VERSION=$(curl https://api.muzlab.ru/api/v1/versioning/last_version \
                | grep -Eo '\:\"(.*)\"' \
                | cut -d: -f2 \
                | cut -d '"' -f2)

if test -z "${REQ_VERSION}"; then echo "Unable to get last stable version"; exit 1; fi

echo "Installing required version...";

REQ_FULL_VERSION=$(apt-cache madison muzlab-client-desktop \
                    | grep $REQ_VERSION \
                    | egrep -o '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\-[[:lower:]]{1,8}\-[[:digit:]]{3}')

if test -z "${REQ_FULL_VERSION}"; then echo "Unable to get required version from repo, exiting"; exit 1; fi

echo "Installing required version...";

apt install -y --allow-downgrades --no-install-recommends --allow-change-held-packages muzlab-client-desktop="${REQ_FULL_VERSION}";

echo "Adding nogui flag to prevent player from rendering gui.. ";

touch /home/mopidy/.muzlab_device_nogui;
systemctl restart desktop_player;

echo "Successfully installed last stable version..";
