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

ROON=/usr/local/Roon
ROONAPI=${ROON}/api
ROONETC=${ROON}/etc
ROONCONF=${ROONETC}/pyroonconf
PLAY=play_artist_album.py
ARTIST=
ALBUM=
EXARTIST=
EXALBUM=

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

cd ${ROONAPI} || exit 1

[ -f $PLAY ] || exit 2

ZONE=
# Parse the arguments to get the zone
while getopts "z:" flag; do
    case $flag in
        z)
            ZONE="$OPTARG"
            ;;
    esac
done
shift $(( OPTIND - 1 ))

# First argument is artist, second is album (required)
# Third optional argument is artist exclusion string (optional)
# Fourth optional argument is album exclusion string (optional)
[ "$1" ] && ARTIST="$1"
[ "$2" ] && ALBUM="$2"
[ "$3" ] && EXARTIST="$3"
[ "$4" ] && EXALBUM="$4"

# 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__"

# Get the default artist if one is not provided
[ "${ARTIST}" ] || {
    ARTIST=$(grep ^DefaultArtist ${ROONETC}/roon_api.ini | awk -F '=' ' { print $2 } ')
    # Remove leading and trailing spaces in ARTIST
    ARTIST="$(echo -e "${ARTIST}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
}

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

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

have_python3=$(type -p python3)
if [ "${have_python3}" ]
then
    python3 $PLAY -A "$ALBUM" -a "$ARTIST" -z "$ROON_ZONE" $EXARGS
else
    python $PLAY -A "$ALBUM" -a "$ARTIST" -z "$ROON_ZONE" $EXARGS
fi

${ROON}/bin/list_album_tracks "${ALBUM}"
