#!/usr/bin/bash

# heos-groups  Copyright 2025  Norman Carver

# Script program to get (and print to stdout) information about
# the current (online) HEOS Groups.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


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

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


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 reformat_groupslist()
{
    cnt=0
    while read line; do
        nameline=${line#*\"name\":\ \"}
        name=${nameline%%\",*}
        gidline=${line#*\"gid\":\ }  #gid value is not quoted
        gid=${gidline%%,*}
        cnt=$((cnt + 1))
        if [[ $cnt -lt 10 ]]; then echo -n " "; fi
        echo "$cnt) Group '$name'  GID:$gid:"
        playerslist=$(grep -Eo '\{[^}]+\}' <<<"${line#*\"players\":\ \[}")
        while read player; do
            player=${player#*\"name\":\ \"}
            name=${player%%\",*}
            player=${player#*\"pid\":\ }
            pid=${player%%,*}
            player=${player#*\"role\":\ \"}
            role=${player%%\"*}
            echo "      player: '$name'  ($role)  PID:$pid"
        done <<< "$playerslist"
    done
}

reformat_groupslist <<<"$groupslist"

#EOF
