#!/usr/bin/bash

# heos-volset  Copyright 2025  Norman Carver

# Script program to Set the Volume on a HEOS player to a Value,
# 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.
#
# Note: volume settings are meaningless for players with Fixed Output set!
# Plus Up/Down commands have no effect on volume settings with Fixed Output.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


volmax=75


function print_usage()
{
    echo "Usage: heos-volset [-g] PLAYER_NAME_OR_IPNUM LEVEL [CONTROLLER_IPNUM]" >&2
    echo "(LEVEL must be 0--50 only)" >&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 [[ $# -lt 2 || $# -gt 3 ]]; then
    print_usage
    exit 1
fi

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

if [[ ! ("$level" =~ ^[0-9]+$ && "$level" -ge 0 && "$level" -le $volmax) ]]; then
    echo "Error: LEVEL must be 0--${volmax} (is '$level')" >&2
    exit 1
fi

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

#EOF
