#!/usr/bin/bash

# heos-players  Copyright 2025  Norman Carver

# Script program to get (print to stdout) information about
# the current (online) HEOS Players.
#
# 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: [-s] heos-players [CONTROLLER_IPNUM]" >&2
    echo "(IPNUM means the last quad of an IP address only: i.e., 0--255)" >&2
    echo "Options:" >&2
    echo "  -s -- sort: print out players info sorted by player Names" >&2
}


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

sort=false
if [[ "$1" == -s ]]; then
    sort=true
    shift
fi

if [[ $# -gt 1 ]]; then
    print_usage
    exit 1
fi

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


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

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

# Sort players (by name) if -s option:
if $sort; then
    playerslist=$(sort <<<"$playerslist")
fi

# Reformat and print out players info:
{ cnt=0
  while read line; do
      nameline=${line#*\"name\":\ \"}
      name=${nameline%%\",*}
      modelline=${line#*\"model\":\ \"}
      model=${modelline%%\",*}
      ipline=${line#*\"ip\":\ \"}
      ip=${ipline%%\",*}
      netline=${line#*\"network\":\ \"}
      net=${netline%%\",*}
      pidline=${line#*\"pid\":\ }  #pid value is not quoted
      pid=${pidline%%,*}
      cnt=$((cnt + 1))
      if [[ $cnt -lt 10 ]]; then echo -n " "; fi
      echo "$cnt) '$name' ($model)    PID:$pid  IP:$ip ($net)"
  done 
} <<< "$playerslist"

#EOF
