#!/usr/bin/bash

# heos-info  Copyright 2025  Norman Carver

# Script program to get (and print to stdout) available Info about
# a (online) HEOS player, 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).
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-info 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

if [[ $# == 0 || $# -gt 2 ]]; then
    print_usage
    exit 1
fi

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


players=$("$heosdir"/heosutil-run-command "heos://player/get_players" $controller)
if [[ ($? != 0) || ("$players" != *'"result": "success"'*) ]]; then
    echo "Error: failed getting HEOS Players info" >&2
    exit 1
fi

playerslist=$(grep -Eo '\{"name":[^}]+}' <<<"$players")

if [[ "$player" =~ ^[0-9]+$ ]]; then
    playerobj=$(grep -E '"ip": "[0-9.]+\.'${player}'"' <<<"$playerslist")
else
    playerobj=$(grep -Ei '"name": "[^"]*'"${player}"'[^"]*"' <<<"$playerslist")
fi

if [[ -z "$playerobj" ]]; then
    echo "Error: no HEOS player matching PLAYER_NAME_OR_IPNUM ('$player')" >&2
    exit 1
fi

# Extract and print out main player info:
attrvallist="${playerobj:1:-1}"
while [[ "$attrval" != "$attrvallist" ]]; do
    attrval=${attrvallist%%,*}
    attrvallist=${attrvallist#*,\ }
    attr=${attrval%:\ *}
    val=${attrval#*:\ }
    echo "${attr:1:-1}=${val}"
done

# Also print out state, volume, and mode (using other HEOS Utils):
"$heosdir"/heos-state "$player"
"$heosdir"/heos-volget "$player"
"$heosdir"/heos-mode "$player"

#EOF
