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

ROON=/usr/local/Roon
ROONAPI=${ROON}/api
ROONETC=${ROON}/etc
ROONCONF=${ROONETC}/pyroonconf
LIST=list_albums.py
ALBUM=
EXALBUM=

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

cd ${ROONAPI} || exit 1

[ -f $LIST ] || exit 2

usage() {
  printf "\nUsage: list_albums [-a album] [-h] [-q] [-t track] [-x exclude] [-z zone] [album] [exclude]"
  printf "\nWhere:"
  printf "\n\t-a 'album' specifies the album title"
  printf "\n\t-h displays this usage message and exits"
  printf "\n\t-q specifies quiet output"
  printf "\n\t-t 'track' specifies a track search term"
  printf "\n\t-x 'exclude' specifies an exclusion search term"
  printf "\n\t-z 'zone' specifies the zone"
  printf "\n\t'album' title can be provided as an argument rather than '-a album'"
  printf "\n\t'exclude' exclusion term can be provided as an argument rather than '-x exclude'\n"
  exit 1
}

listargs=
trackargs=
TRACK=
ZONE=
# Parse the arguments to get the zone
while getopts "a:hqt:x:z:" flag; do
    case $flag in
        a)
            ALBUM="$OPTARG"
            ;;
        h)
            usage
            ;;
        t)
            TRACK="$OPTARG"
            ;;
        x)
            EXALBUM="$OPTARG"
            ;;
        z)
            ZONE="$OPTARG"
            ;;
        q)
            listargs="-q"
            ;;
    esac
done
shift $(( OPTIND - 1 ))

# First argument is album name/substring, Second argument is album exclusion string
[ "$1" ] && ALBUM="$1"
[ "$2" ] && EXALBUM="$2"

# 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:]]*$//')"

# Get the zone if it is set
if [ -f ${ROONCONF} ]
then
    . ${ROONCONF}
else
    ${ROON}/bin/set_zone "${DEFZONE}"
    . ${ROONCONF}
fi

[ "${ZONE}" ] && {
    if [ "${ZONE}" == "default" ]; then
        ROON_ZONE="${DEFZONE}"
    else
        [ "${ZONE}" == "last" ] || ROON_ZONE="${ZONE}"
    fi
}
# Use all zones if no zone is specified or set
[ "${ROON_ZONE}" ] || ROON_ZONE="__all__"

[ "${ALBUM}" ] || ALBUM="__all__"

# Construct the exclusion args if passed
EXARGS="${listargs}"
[ "${EXALBUM}" ] && EXARGS="${EXARGS} -x ${EXALBUM}"

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

if [ "${TRACK}" ]; then
    ${PYTHON} $LIST -a "$ALBUM" -t "${TRACK}" -z "$ROON_ZONE" $EXARGS
else
    ${PYTHON} $LIST -a "$ALBUM" -z "$ROON_ZONE" $EXARGS
fi
