#!/bin/bash
#
# shellcheck disable=SC1090,SC2220

ROON=/usr/local/Roon
ROONAPI=${ROON}/api
ROONETC=${ROON}/etc
ROONCONF=${ROONETC}/pyroonconf
NOWP=now_playing.py
ZONE=

[ -d ${ROONAPI} ] || exit 1

cd ${ROONAPI} || exit 1

[ -f $NOWP ] || exit 2

usage() {
  printf "\nUsage: now_playing [-a] [-h] [-p] [-P] [-z ZONE]"
  printf "\nWhere:"
  printf "\n\t-a indicates all states"
  printf "\n\t-p indicates list only playing states"
  printf "\n\t-P indicates list only paused states"
  printf "\n\t-z ZONE specifies the Roon zone in which to query"
  printf "\n\t   '-z default' indicates the default zone, '-z last' the last zone used"
  printf "\n\t-h displays this usage message and exits\n\n"
  exit 1
}

# Use a Python virtual environment
[ -f ${ROON}/venv/bin/activate ] && source ${ROON}/venv/bin/activate
[[ ":$PATH:" == *":/usr/local/Roon/venv/bin:"* ]] || {
  export PATH=/usr/local/Roon/venv/bin:${PATH}
}

DEFZONE=$(grep ^DefaultZone ${ROONETC}/roon_api.ini | awk -F '=' ' { print $2 } ')
# Remove leading and trailing spaces in DEFZONE
DEFZONE="$(echo -e "${DEFZONE}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"

if [ -f ${ROONCONF} ]; then
  . ${ROONCONF}
else
  ${ROON}/bin/set_zone "${DEFZONE}"
  . ${ROONCONF}
fi

aflag=
pflag=
while getopts "ahpPz:" flag; do
  case $flag in
    z)
      ZONE="$OPTARG"
      ;;
    a)
      aflag="-a"
      ;;
    h)
      usage
      ;;
    p)
      pflag="-p"
      ;;
    P)
      pflag="-P"
      ;;
  esac
done

[ "${ZONE}" ] && {
    if [ "${ZONE}" == "default" ]; then
        ROON_ZONE="${DEFZONE}"
    else
        [ "${ZONE}" == "last" ] || ROON_ZONE="${ZONE}"
    fi
}

# Get all zones if no zone is specified
[ "${ZONE}" ] || ROON_ZONE="__all__"

have_python3=$(type -p python3)
if [ "${have_python3}" ]; then
  PYTHON=python3
else
  PYTHON=python
fi

have_rich=$(type -p rich)
if [ "${have_rich}" ]; then
  ${PYTHON} $NOWP ${aflag} ${pflag} -z "${ROON_ZONE}" | while read lin; do
    if echo "${lin}" | grep : > /dev/null; then
      key=$(echo "${lin}" | awk -F ':' '{ print $1 }')
      key="$(echo -e "${key}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
      val=$(echo "${lin}" | awk -F ':' '{ print $2 }')
      val="$(echo -e "${val}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
      val="$(echo -e "${val}" | sed -e 's/^\"//' -e 's/\"$//')"
      if echo "${key}" | grep Now > /dev/null; then
        pre=""
        siz=19
      else
        pre="    "
        siz=15
      fi
      numspaces=$((${siz} - ${#key}))
      spaces=""
      for i in $(seq ${numspaces}); do
        spaces="${spaces} "
      done
      rich "${pre}[red]${key}[/]:${spaces} [yellow]${val}[/]" -p
    else
      rich "[yellow]${lin}[/]" -p
    fi
  done
else
  ${PYTHON} $NOWP ${aflag} ${pflag} -z "${ROON_ZONE}"
fi
