#!/usr/bin/bash

# heos-voldown  Copyright 2025  Norman Carver

# Script program to Lower the Volume 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.
#
# 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.


function print_usage()
{
    echo "Usage: heos-voldown [-g] PLAYER_NAME_OR_IPNUM [STEPS [CONTROLLER_IPNUM]]" >&2
    echo "(STEPS from 1--10, default is 5)" >&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 3 ]]; then
    print_usage
    exit 1
fi

player=$1
if [[ $# -ge 2 ]]; then
    steps=${2}
    if [[ ! ("$steps" =~ ^[0-9]+$ && "$steps" -ge 1 && "$steps" -le 10) ]]; then
        echo "Error: STEPS must be from 1--10" >&2
        exit 1
    fi
fi
if [[ $# == 3 ]]; then
    controllern=${3}
else
    controller=""
fi
heosdir=$(dirname "$0")


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

#EOF
