#!/usr/bin/bash

# heos-favlist  Copyright 2025  Norman Carver

# Script program to Browse the HEOS Favorites (as set in the HEOS app),
# i.e., to print to stdout the list of Favorites.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


function print_usage()
{
    echo "Usage: heos-favlist [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

if [[ $# -gt 1 ]]; then
    print_usage
    exit 1
fi

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


# Functions used below:
function line_2() { read; read line; echo "$line"; }


# Get Music Sources info so can get Favorites SID:
sources=$("$heosdir"/heosutil-run-command "heos://browse/get_music_sources" $controller)
if [[ ($? != 0) || ("${sources}" != *'"result": "success"'*) ]]; then
    echo "Error: failed getting Music Sources listing" >&2
    exit 1
fi

favsrc=${sources#*\{\"name\": \"Favorites\"*\"sid\":\ }
favsid=${favsrc%%,*}

# Get Favorites browse list (list is in 2nd JSON response):
favjson=$("$heosdir"/heosutil-run-command --numjson=2 "heos://browse/browse?sid=${favsid}" $controller | line_2)
if [[ ($? != 0) || ("${favjson}" != *'"result": "success"'*) ]]; then
    echo "Error: failed getting Favorites listing" >&2
    exit 1
fi

# Make list on separate lines of the favorites objects:
favlist=$(grep -Eo '\{"container": [^}]+\}' <<<"$favjson")


# Reformat and output favlist:
{ cnt=0
  while read line; do
      line=${line#*\"type\":\ \"}
      type=${line%%\",*}
      line=${line##*\"name\":\ \"}
      name=${line%%\",*}
      cnt=$((cnt + 1))
      if [[ $cnt -lt 10 ]]; then echo -n " "; fi
      echo "$cnt) $type: $name"
  done 
} <<<"$favlist"

#EOF
