#!/usr/bin/bash

# heos-names  Copyright 2025  Norman Carver

# Script program to get (print to stdout) information about
# the current (online) HEOS Players names.
#
# The output is sorted.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-names [-s] [-g] [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 Player/Group Names sorted" >&2
    echo "  -g -- groups: print out Group Names (rather than Player Names)" >&2
}


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

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

group=false
if [[ "$1" == -g ]]; then
    group=true
    shift
fi

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

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

if ! $group; then
    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")


    function player_names_from_playerslist()
    {
        while read line; do
            line=${line#*\"name\":\ \"}
            echo "${line%%\",*}"
        done 
    }

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

    # Reformat and print out player names:
    player_names_from_playerslist <<<"$playerslist"

else

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

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


    function group_names_from_groupslist()
    {
        while read line; do
            line=${line#*\"name\":\ \"}
            echo "${line%%\",*}"
        done
    }


    group_names_from_groupslist <<<"$groupslist" | sort
fi

#EOF
