#!/usr/bin/bash

# heos-mutetoggle  Copyright 2025  Norman Carver

# Script program to Toggle Mute on a HEOS player, where the player is specified with:
# (1) a (sub)string of the player's HEOS name, or
# (2) its IP num (i.e., host portion of its dotted quad IP address).
#
# If the "player" is actually a HEOS Group, use the -g option
# with the "player" name being the group name.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-mutetoggle [-g] PLAYER_NAME_OR_IPNUM [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

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

if [[ $# == 0 || $# -gt 2 ]]; then
    print_usage
    exit 1
fi

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


if ! $group; then
    result=$("$heosdir"/heosutil-run-command --player="$player" "heos://player/toggle_mute?pid=\${pid}" $controller)
else
    result=$("$heosdir"/heosutil-run-command --player="$player" --group "heos://group/toggle_mute?gid=\${gid}" $controller)
fi
if [[ ($? != 0) || ("$result" != *'"result": "success"'*) ]]; then
    echo "Action FAILED!" >&2
    exit 1
fi

#EOF
