#!/usr/bin/bash

# heos-players  Copyright 2025-2026  Norman Carver

# Script program to print (to stdout) information about the current (online) HEOS Players.
#
# Sends commands to the default HEOS master device, but can select alternative
# using the MASTER_IPNUM argument option.


function print_usage()
{
    echo -e "Print information about the current HEOS Players.\n" >&2
    echo    "Usage: heos-players [-n] [-s] [MASTER_IPNUM]" >&2
    echo    "where:" >&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    "  -n -- names: print out only player Names;" >&2
    echo    "  -s -- sort: print out players info sorted by names (uses system sort command);" >&2
}


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

# Process supplied options:
names=false
sort=false
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$1" == -n ]]; then
        names=true
    elif [[ "$1" == -s ]]; then
        sort=true
    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 [[ $# -gt 1 ]]; then
    print_usage
    exit 1
fi

if [[ $# == 1 ]]; then
    master=${1}
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
}


# Get Players info (in JSON format):
playersjson=$("$heosdir"/heosutils/heosutil-run-command "heos://player/get_players" $master)
error_check_run_command playersjson "Error: failed getting HEOS Players!"

# Extract Payload info:
payload=$(grep -Eo '"payload": \[[^]]+\]' <<< "$playersjson")

# Use grep to make line-based list of the players:
playerslist=$(grep -Eo '\{"name": [^}]+\}' <<<"$payload")

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

if ! $names; then
    # Reformat and print out players info:
    { cnt=0
      while read line; do
          name=${line#*\"name\":\ \"}
          name=${name%%\"[,\}]*}
          model=${line#*\"model\":\ \"}
          model=${model%%\"[,\}]*}
          ip=${line#*\"ip\":\ \"}
          ip=${ip%%\"[,\}]*}
          net=${line#*\"network\":\ \"}
          net=${net%%\"[,\}]*}
          pid=${line#*\"pid\":\ }  #pid value is not quoted
          pid=${pid%%[,\}]*}
          cnt=$((cnt + 1))
          printf "%2d) %-27s %-17s  PID:%-12s  IP:%s (%s)\n" $cnt "'${name}'" "(${model})" "$pid" "$ip" "$net"
      done 
    } <<< "$playerslist"

else
    # Print out players names:
    { while read line; do
          line=${line#*\"name\":\ \"}
          echo "${line%%\"[,\}]*}"
      done 
    } <<< "$playerslist"

fi

#EOF
