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

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

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

cd ${ROONAPI} || exit 1

[ -f $LIST ] || exit 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:]]*$//')"

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

[ "$1" ] && ZONE="$*"

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

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

have_python3=$(type -p python3)
if [ "${have_python3}" ]
then
    python3 $LIST -g -z "${ZONE}"
else
    python $LIST -g -z "${ZONE}"
fi
