#!/usr/bin/bash

# heos-qplay  Copyright 2025-2026  Norman Carver

# Script program to Play a particular Queue item on a HEOS player/group.
#
# A 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).
#
# With the -g option, a group is specified:
# (1) a (sub)string of the group's HEOS name, or
# (2) its Group ID (GID).
#
# Sends commands to the default HEOS master device, but can select alternative
# using the MASTER_IPNUM argument option.


function print_usage()
{
    echo -e "Play a particular HEOS Queue item on a HEOS Player/Group.\n" >&2
    echo    "Usage: heos-qplay [-g] [-v] PLAYER QUEUE_ITEM [MASTER_IPNUM]" >&2
    echo    "where:" >&2
    echo    "  PLAYER -- a HEOS Player's Name (substring) or its IPNUM;" >&2
    echo    "  QUEUE_ITEM -- the 1-based index number of an item in the Queue;" >&2
    echo    "  MASTER_IPNUM -- use a non-default HEOS master device;" >&2
    echo -e "  (IPNUM means the last quad of an IP address only: i.e., 0--255.)\n" >&2
    echo    "Options:" >&2
    echo    "  -g -- group: PLAYER is a group Name or GID;" >&2
    echo    "  -v -- verbose: print out name of QUEUE_ITEM_ID when started;" >&2
}


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

# Process supplied options:
pgopt=--player
verbose=false
pidopt=""
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$1" == -g ]]; then
        pgopt=--group
    elif [[ "$1" == -v ]]; then
        verbose=true
    elif [[ "$1" == --pid=?* ]]; then
        pidopt=$1
    elif [[ "$1" == -- ]]; then
        shift;break
    elif [[ "$1" == --debug ]]; then
        debugopt=--debug
    else
        echo "Error: invalid option '$1'" >&2
        echo "(use '--' to signal end of options, with -* arguments)" >&2
        exit 1 
    fi
    shift
done

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

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


# heosutil-run-command error checking function (one json output):
# args: 1) command result variable; 2) error message; [3) error action]
# (default action on error is 'exit 1', use $3 of 'return 1' to continue execution)
function error_check_run_command()
{
    cmdresult=${!1}
    if [[ ($? != 0) || ("$cmdresult" != *'"result": "success"'*) ]]; then
        if [[ "$cmdresult" == Error:* || ($debugopt == --debug && "$cmdresult" == ERROR:*) ]]; then
            echo "$cmdresult" >&2
        fi
        if [[ -n "$2" ]]; then echo "$2" >&2; fi
        if [[ $# == 3 ]]; then $3; else exit 1; fi
    else
        return 0
    fi
}

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


# Start Queue track QUEUE_ITEM_ID playing:
result=$("$heosdir"/heosutils/heosutil-run-command ${pgopt}="$player" $pidopt "heos://player/play_queue?pid=\${pid}&qid=$itemnum" $master)
if ! error_check_run_command result "" "return 1"; then
    # Get Queue to check if it is empty:
    qjson=$("$heosdir"/heosutils/heosutil-run-command ${pgopt}="$player" $pidopt "heos://player/get_queue?pid=\${pid}" $master)
    if error_check_run_command qjson "check failed" "return 1" && [[ "$qjson" == *\&count=0\"* ]]; then
        echo "Error: Queue is Empty on HEOS player '$player'!" >&2
    else
        echo "Error: failed playing QUEUE_ITEM ('$itemnum') on PLAYER ('$player')!" >&2
    fi
    exit 1
fi

# Check if need to print out name of QUEUE_ITEM_ID:
if $verbose; then
    # Get Queue item (in JSON format):
    itemindex=$((itemnum-1))
    browse=$("$heosdir"/heosutils/heosutil-run-command ${pgopt}="$player" $pidopt "heos://player/get_queue?pid=\${pid}&range=$itemindex,$itemindex" $master)
    error_check_run_command browse "Error: failed getting Queue for HEOS player '$player'!"

    # Use grep to make get item json:
    itemjson=$(grep -Eo '\{[^}]*"song":[^}]+\}' <<<"$browse")
    if [[ -z "$itemjson" ]]; then
        echo "Error: no QUEUE_ITEM '$itemnum'!" >&2
        exit 1
    fi

    # Reformat and print out itemjson:
    song=${itemjson#*\"song\":\ \"}
    song=${song%%\"[,\}]*}
    album=${itemjson#*\"album\":\ \"}
    album=${album%%\"[,\}]*}
    artist=${itemjson#*\"artist\":\ \"}
    artist=${artist%%\"[,\}]*}
    echo "Playing Queue item: $artist: \"$song\"  (from \"$album\")..."

else
    echo "Playing Queue item #${itemnum}..."
fi

#EOF
