#!/bin/bash
#
# shellcheck disable=SC1090,SC2220,SC2207,SC2068,SC2001

uninstall() {
  LOCAL="/usr/local"
  APPL=${LOCAL}/share/applications
  DOC=${LOCAL}/share/doc
  ROON=${LOCAL}/Roon
  ROONBIN=${ROON}/bin

  [ -d /usr/local/bin ] && {
    cd /usr/local/bin || exit 1
    for command in "${ROONBIN}"/*
    do
      [ "${command}" == "${ROONBIN}/*" ] && continue
      b=$(basename "${command}")
      [ -L "$b" ] && {
        /bin/ls -l "$b" | grep ${ROON} > /dev/null && sudo rm -f "$b"
      }
    done
  }

  sudo rm -rf ${ROON}
  sudo rm -rf ${DOC}/RoonCommandLine
  sudo rm -f ${APPL}/rooncommand.desktop

  echo ""
  echo "RoonCommandLine uninstalled"
}

have_fade=$(type -p roon_fade)
[ "${have_fade}" ] && roon_fade off

plat=$(uname -s)
if [ "$plat" == "Darwin" ]
then
  uninstall
else
  debian=
  have_apt=$(type -p apt)
  have_dpkg=$(type -p dpkg)
  have_rpm=$(type -p rpm)
  have_yum=$(type -p yum)
  [ -f /etc/os-release ] && . /etc/os-release
  [ "${ID_LIKE}" == "debian" ] && debian=1
  [ "${debian}" ] || [ -f /etc/debian_version ] && debian=1

  PKG=rooncommandline
  [ "${debian}" ] || PKG=RoonCommandLine

  if [ "${debian}" ]
  then
    if [ "${have_apt}" ]
    then
      sudo apt remove "${PKG}" -y > /dev/null 2>&1
    else
      if [ "${have_dpkg}" ]
      then
        sudo dpkg -r "${PKG}" > /dev/null 2>&1
      else
        echo "Cannot locate either apt or dpkg to remove. Skipping."
      fi
    fi
  else
    if [ "${have_yum}" ]
    then
      sudo yum remove "${PKG}" > /dev/null 2>&1
    else
      if [ "${have_rpm}" ]
      then
        sudo rpm -e "${PKG}" > /dev/null 2>&1
      else
        echo "Cannot locate either yum or rpm to remove. Skipping."
      fi
    fi
  fi
  uninstall
fi
