#!/bin/bash
MUZLAB_REPO="/etc/apt/sources.list.d/muzlab.list";
REPO_LIST="sources.list.d/muzlab.list";
OS_ARCH=$(uname -m)

if [ "${OS_ARCH}" == "x86_64" ]; then
  REPO_OS="focal"
elif [ "${OS_ARCH}" == "armv7l" ]; then
  REPO_OS="buster"
else
  echo "Unknown arch ${OS_ARCH}"; exit 1;
fi

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 ${REPO_OS} 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 player package to hold packages to prevent os from updating it.. ";
echo "muzlab-client-desktop hold" | dpkg --set-selections;

if [ "${REPO_OS}" == "buster" ]; then
echo "Altering alsa parameters.. ";
cat << EOF > /etc/asound.conf
defaults.pcm.card 0
defaults.ctl.card 0
EOF
fi

function checkhwclock {
  /sbin/hwclock -r > /dev/null 2>&1;
  if [[ $? -ne 0 ]]; then return 1; fi

  echo "Any do" >> /tmp/hwclock;
  LINE=$(grep -n "/run/systemd/system" /lib/udev/hwclock-set);
  if [[ $(echo $LINE |grep -c '#') -eq 0 ]]; then
      START=$(echo $LINE |cut -f1 -d:);
      END=$(($START + 2));
      echo $START $END;
      sed "$START,$END {s/^/#/}" /lib/udev/hwclock-set -i;
  fi

  if [[ $(systemctl is-enabled fake-hwclock |grep -c "enabled") -eq 1 ]]; then
      systemctl disable --now fake-hwclock
  fi

  if [[ $(dpkg -l |grep fake-hwclock -c) -eq 1 ]]; then
      echo "delete fake-hwclock"
      apt remove -y fake-hwclock
  fi
}

if [ "${REPO_OS}" == "buster" ]; then
  echo "Checking rtc clock.. ";
  checkhwclock;
fi

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, rebooting.. ";
reboot
