#!/usr/bin/bash

# heos-ungroup  Copyright 2025-2026  Norman Carver

# Script program to Ungroup a set of Players currently in a HEOS Group.
#
# Specify the Group using the Group's HEOS name or GID.
#
# Sends commands to the default HEOS master device, but can select alternative
# using the MASTER_IPNUM argument option.


function print_usage()
{
    echo -e "UnGroup the players from a current HEOS Group.\n" >&2
    echo    "Usage: heos-ungroup GROUP [MASTER_IPNUM]" >&2
    echo    "where:" >&2
    echo    "  GROUP -- a current HEOS group name or the group's GID (Group ID) number;" >&2
    echo    "  MASTER_IPNUM -- use a non-default HEOS master device;" >&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

# Catch invalid supplied options:
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$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
done

# Process command arguments:
if [[ $# -lt 1 || $# -gt 2 ]]; then
    print_usage
    exit 1
fi

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


# UnGroup the players in the specified group:
result=$("$heosdir"/heosutils/heosutil-run-command --group="$group" "heos://group/set_group?pid=\${gid}" $master)
error_check_run_command result "Error: failed to ungroup players from group '$group'!"

#EOF
