#!/usr/bin/bash

# heos-qplay  Copyright 2025  Norman Carver

# Script program to Play a particular Queue item,
# where the player is specified with:
# (1) a (sub)string of the player's HEOS name, or
# (2) its IP num (i.e., host portion of its dotted quad IP address).
#
# If the "player" is actually a HEOS Group, use the -g option
# with the "player" name being the group name.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-qplay [-g] PLAYER_NAME_OR_IPNUM QUEUE_TRACK_ID [CONTROLLER_IPNUM]" >&2
    echo "(IPNUM means the last quad of an IP address only: i.e., 0--255)" >&2
}


if [[ "$1" == --help ]]; then
    print_usage
    exit 0
fi

groupopt=
if [[ "$1" == -g ]]; then
    groupopt=--group
    shift
fi

if [[ $# -lt 2 || $# -gt 3 ]]; then
    print_usage
    exit 1
fi

player=$1
qid=$2
if [[ $# == 3 ]]; then
    controller=${3}
else
    controller=""
fi
heosdir=$(dirname "$0")

if [[ ! "$qid" =~ ^[0-9]+$ ]]; then
    echo "Error: QID must be an integer >= 1 (is '$qid')" >&2
    exit 1
fi


# Start Queue song QUEUE_TRACK_ID playing:
result=$("$heosdir"/heosutil-run-command --player="$player" $groupopt "heos://player/play_queue?pid=\${pid}\&qid=$qid" $controller)
if [[ ($? != 0) || ("$result" != *'"result": "success"'*) ]]; then
    echo "Action FAILED!" >&2
    exit 1
fi

#EOF
