#!/usr/bin/bash

# heos-stop  Copyright 2025  Norman Carver

# Script program to Stop play 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-stop [-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

groupopt=
if [[ "$1" == -g ]]; then
    groupopt=--group
    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")


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

#EOF
