#!/usr/bin/bash

# heos-qlist  Copyright 2025  Norman Carver

# Script program to print to stdout information about the Queue,
# 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.
#
# The output is pretty-printed JSON as provided by a HEOS controller.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-qlist [-g] PLAYER_NAME_OR_IPNUM [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 [[ $# == 0 || $# -gt 2 ]]; then
    print_usage
    exit 1
fi

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


# Get Queue songs list for Player:
qjson=$("$heosdir"/heosutil-run-command --player="$player" $groupopt "heos://player/get_queue?pid=\${pid}" $controller)
if [[ ($? != 0) || ("$qjson" != *'"result": "success"'*) ]]; then
    echo "Error: failed getting HEOS player's Queue" >&2
    exit 1
fi

# Make list on separate lines of the queue song objects:
qlist=$(grep -Eo '\{"song": [^}]+\}' <<<"$qjson")

# Reformat and output qlist:
{ cnt=0
  while read line; do
      songline=${line#*\"song\":\ \"}
      song=${songline%%\",*}
      albumline=${line#*\"album\":\ \"}
      album=${albumline%%\",*}
      artistline=${line#*\"artist\":\ \"}
      artist=${artistline%%\",*}
      cnt=$((cnt + 1))
      if [[ $cnt -lt 10 ]]; then echo -n " "; fi
      echo "$cnt) $artist: \"$song\"  (from \"$album\")"
  done 
} <<<"$qlist"

#EOF
