#!/usr/bin/bash

# heos-nowplaying  Copyright 2025  Norman Carver

# Script program to print to stdout information about
# the current music playing 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.
#
# The output is pretty-printed JSON as provided by a HEOS controller.
#
# Sends commands to the default HEOS controller, but can select alternative
# using the CONTROLLER_IPNUM argument option.


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


playingjson=$("$heosdir"/heosutil-run-command --player="$player" $groupopt "heos://player/get_now_playing_media?pid=\${pid}" $controller)
if [[ ($? != 0) || ("$playingjson" != *'"result": "success"'*) ]]; then
    echo "Error: failed to retrieve Now Playing info from Player/Group ('$player')" >&2
    exit 1
fi

playing=${playingjson#*\"payload\":\ \{}
playing=${playing%\},\ \"options\"*}


# Reformat and output playing:
# (playing json format: (type song [station] album artist ... qid sid))
{ playing=${playing#*\"type\":\ \"}
  type=${playing%%\",\ *}
  playing=${playing#*\"song\":\ \"}
  song=${playing%%\",\ *}
  stationp=false
  if [[ "$type" == station ]]; then
      stationp=true
      playing=${playing#*\"station\":\ \"}
      station=${playing%%\",\ *}
  fi
  playing=${playing#*\"album\":\ \"}
  album=${playing%%\",\ *}
  playing=${playing#*\"artist\":\ \"}
  artist=${playing%%\",\ *}
  playing=${playing#*\"qid\":\ }
  qid=${playing%%,\ *}

  if $stationp; then echo "Station: $station"; fi
  if [[ -n "$artist" ]]; then
      echo "Song:    $song"
      if [[ -n "$album" ]]; then echo "Album:   $album"; fi
      echo "Artist:  $artist"
  fi
  if ! $stationp; then echo "QID: $qid"; fi
} <<<"$playing"

#EOF
