#!/usr/bin/bash

# heos-histplay  Copyright 2025-2026  Norman Carver

# Script program to Play a particular HEOS History item on a HEOS player/group.
#
# A 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).
#
# With the -g option, a group is specified:
# (1) a (sub)string of the group's HEOS name, or
# (2) its Group ID (GID).
#
# Sends commands to the default HEOS master device, but can select alternative
# using the MASTER_IPNUM argument option.
#
# The HEOS History is NOT exactly the same as the HEOS app Recents.
# The app Recents consists of four categories: Tracks, Stations,
# Albums, Playlists, as well as All (that shows all categories).
# History allows one to view only Tracks and Stations, so recent
# plays under Albums and Playlists cannot be listed.  Playing items
# from Local (DLNA) Server seems to put things under Albums even when
# just a single track is played, so don't show in History.


# Source ID (SID) for History (from HEOS Protocol doc):
# (Set it to empty string to cause it to be determined from Music Sources.)
sid_history=1026


function print_usage()
{
    echo    "Play a particular HEOS History item on a HEOS Player/Group." >&2
    echo -e "(Track item is added to Player's Queue and play started.)\n" >&2
    echo    "Usage: heos-histplay [-g] [-s] [-v] PLAYER HISTORY_ITEM  [MASTER_IPNUM]" >&2
    echo    "where:" >&2
    echo    "  PLAYER -- a HEOS Player's Name (substring) or its IPNUM;" >&2
    echo    "  HISTORY_ITEM -- the 1-based index number of an item in the  list;" >&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
    echo    "Options:" >&2
    echo    "  -g -- group: PLAYER is a group Name or GID;" >&2
    echo    "  -s -- station: item is from Stations History instead of Tracks;" >&2
    echo    "  -v -- verbose: print out name of HISTORY_ITEM when started;" >&2
}


if [[ "$1" == --help ]]; then
    print_usage
    exit 0
fi

# Process supplied options:
pgopt=--player
cid=TRACKS
verbose=false
pidopt=""
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$1" == -g ]]; then
        pgopt=--group
    elif [[ "$1" == -s ]]; then
        cid=STATIONS
    elif [[ "$1" == -v ]]; then
        verbose=true
    elif [[ "$1" == --pid=?* ]]; then
        pidopt=$1
    elif [[ "$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
    shift
done

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

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


# heosutil-run-command error checking function (two json outputs):
# 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_2json()
{
    cmdresult=${!1}
    if [[ ($? != 0) || ("$cmdresult" != *'"result": "success"'*'"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
}


if [[ ! ("$itemnum" =~ ^[0-9]+$ && "$itemnum" -ge 1) ]]; then
    echo "Error: HISTORY_ITEM must be an integer >= 1 ('$itemnum')!" >&2
    exit 1
fi


# If necessary, determine History SID from Music Sources:
if [[ -z "$sid_history" ]]; then
    # Get Music Sources info so can get History SID:
    sources=$("$heosdir"/heosutils/heosutil-run-command "heos://browse/get_music_sources" $master)
    error_check_run_command sources "Error: failed getting Music Sources listing!"
    sid_history=${sources#*\{\"name\": \"History\"*\"sid\":\ }
    sid_history=${sid_history%%[,\}]*}
fi

# Get HISTORY_ITEM from browse list using its index (action result in 2nd JSON object):
itemindex=$((itemnum-1))
browse=$("$heosdir"/heosutils/heosutil-run-command --numjson=2 "heos://browse/browse?sid=${sid_history}&cid=${cid}&range=$itemindex,$itemindex" $master)
error_check_run_command_2json browse "Error: failed getting HISTORY_ITEM ('$itemnum') info!"

# Extract the specific item JSON to ensure correct parsing:
itemjson=$(grep -Eo '\{[^}]*"container":[^}]+\}' <<<"$browse")
if [[ -z "$itemjson" ]]; then
    echo "Error: failed extracting HISTORY_ITEM info!" >&2
    exit 1
fi

# Get mid from itemjson:
mid=${itemjson#*\"mid\":\ \"}
mid=${mid%%\",*}

# Start HISTORY_ITEM playing (action result in 2nd JSON object):
if [[ "$cid" == TRACKS ]]; then
    result=$("$heosdir"/heosutils/heosutil-run-command ${pgopt}="$player" $pidopt --numjson=2 "heos://browse/add_to_queue?pid=\${pid}&sid=${sid_history}&cid=${cid}&mid=${mid}&aid=1" $master)
else
    result=$("$heosdir"/heosutils/heosutil-run-command ${pgopt}="$player" $pidopt --numjson=2 "heos://browse/play_stream?pid=\${pid}&sid=${sid_history}&cid=${cid}&mid=${mid}" $master)
fi
error_check_run_command_2json result "Error: failed playing HISTORY_ITEM ('$itemnum') on PLAYER ('$player')!"

# Print out HISTORY_ITEM if selected:
if $verbose; then
    # Get song info from browse:
    type=${itemjson#*\"type\":\ \"}
    type=${type%%\",*}
    name=${itemjson##*\"name\":\ \"}
    name=${name%%\",*}
    if [[ "$cid" == TRACKS ]]; then
        echo "Adding History item '$type: $name' to queue and playing..."
    else
        echo "Playing History item '$type: $name'..."
    fi

else
    echo "Playing History item #${itemnum}..."
fi

#EOF
