#!/usr/bin/bash

# heos-pllist  Copyright 2025-2026  Norman Carver

# Script program to Browse the HEOS Playlists (as set in the HEOS app),
# i.e., to print (to stdout) the list of PlayLists.
#
# Sends commands to the default HEOS master device, but can select alternative
# using the MASTER_IPNUM argument option.


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


function print_usage()
{
    echo -e "Print a list of the HEOS Playlists.\n" >&2
    echo    "Usage: heos-pllist [MASTER_IPNUM]" >&2
    echo    "where:" >&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
}


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

# Catch invalid supplied options:
debugopt=""
while [[ "$1" == -* ]]; do
    if [[ "$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
done

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

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


# Determine Playlists SID from Music Sources if necessary:
if [[ -z "$sid_playlists" ]]; then
    # Get Music Sources info so can get Playlists 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=${sources#*\{\"name\": \"Playlists\"*\"sid\":\ }
    sid_playlists=${sid%%[,\}]*}
fi

# Get Playlists browse list (action result in 2nd JSON object):
browse=$("$heosdir"/heosutils/heosutil-run-command --numjson=2 "heos://browse/browse?sid=${sid_playlists}" $master)
error_check_run_command_2json browse "Error: failed getting Playlists info!"

# Get number of available items:
count=$(grep -Eo 'count=[0-9]+' <<<"$browse")
if [[ "$count" == "count=0" ]]; then
    echo "Error: HEOS Playlists is Empty!" >&2
    exit 1
fi

# Extract Payload info:
payload=$(grep -Eo '"payload": \[.+\][,}]' <<<"$browse")

# Make list on separate lines of the Playlists objects:
itemslist=$(grep -Eo '\{"container": [^}]+\}' <<<"$payload")
if [[ -z "$itemslist" ]]; then
    echo "Error: failed extracting HEOS Playlists, try again!" >&2
    exit 1
fi

# Reformat and print out Playlists list:
{ cnt=0
  while read line; do
      name=${line##*\"name\":\ \"}
      name=${name%%\"[,\}]*}
      cnt=$((cnt + 1))
      printf "%2d) %s\n" $cnt "$name"
  done 
} <<<"$itemslist"

#EOF
