#!/usr/bin/bash

# heos-pllist  Copyright 2025  Norman Carver

# Script program to Browse the Playlists, i.e., to print to stdout the list of PlayLists.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


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

plsrc=${sources#*\{\"name\": \"Playlists\"*\"sid\":\ }
plsid=${plsrc%%,*}

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

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

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

#EOF
