#!/bin/sh
###
### cmus-sd.sh (based on examples/cmus-status-display)
###
### cmus-status-display
###
### Usage:
###   in cmus command ":set status_display_program=cmus-status-display"
###
### If called as 'cmus-rstat.sh', the script outputs the contents of the
### configured status file to stdout.
###
### This scripts is executed by cmus when status changes:
###   cmus-status-display key1 val1 key2 val2 ...
###
### All keys contain only chars a-z. Values are _UTF-8_ strings.
###
### Keys: status file url artist album discnumber tracknumber title date
###   - status (stopped, playing, paused) is always given
###   - file or url is given only if track is 'loaded' in cmus
###   - other keys/values are given only if they are available
###

# if USE_SHM is > zero, the script will try to put the status file to
# /dev/shm/$USER_NAME/, which is on a tmpfs on my system:
#   tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)
# else, the status file will be written to ~/tmp/.
USE_SHM=1
OUTPUT="$HOME/tmp/cmus-status"
NAME="${USER:-$LOGNAME}"
[ -z "$NAME" ] && NAME="$(id -nu)"

if [ "${USE_SHM}" -gt 0 ] ; then
    [ ! -d "/dev/shm/$NAME" ] && mkdir -p "/dev/shm/$NAME"
    OUTPUT="/dev/shm/$NAME/cmus-status"
fi

case "${0}" in
    *cmus-rstat.sh)
        if [ -e "${OUTPUT}" ] ; then
            if [ "${1}" = '-fvwm' ] ; then
                printf '%s\n' "${OUTPUT}"
            else
                cat "${OUTPUT}"
            fi
        else
            printf '%s not found. No now-playing information. Sorry.\n' \
                    "${OUTPUT}"
            exit 1
        fi
        exit 0
        ;;
    *)
        : nop
        ;;
esac

output() {
  ### write last status to $OUTPUT
  ### I am using this file in various apps:
  ### e.g.: irssi /np or my cmus submenu in my fvwm menu
  echo "$@" > "${OUTPUT}"  2>&1
}

while [ "$#" -ge 2 ] ; do
  ### $_key='val'
  eval _$1='$2'
  shift
  shift
done

if [ "$_status" = 'playing' ] ; then
  if   [ -n "$_file" ] ; then
    ### when we're playing a file...
    [ -n "$_album" ] && output "np: $_artist - $_album - $_title" || output "np: $_artist - $_title"
    #output "np: $_artist - $_title"
  elif [ -n "$_url"  ] ; then
    ### streaming from the net
    output "np: $_title"
  else
    ### shouldn't get this far...
    : ;
  fi
else
  ### when we're not playing, tell what we're doing
  output "[cmus]: -$_status-"
fi