#!/bin/sh
# media module -- MPRIS media controls via playerctl (works with most
# players automatically: Spotify, VLC, mpv, Firefox/Chromium tabs, etc.),
# dispatched by subcommand. Controls whichever player playerctl considers
# active (usually whichever was most recently active) -- run `playerctl -l`
# yourself to see all available players if you run more than one at once.
#   media.sh            -> bar text: play/pause glyph + "Artist - Title"
#   media.sh track      -> "Artist - Title", undecorated (popup info row)
#   media.sh art        -> path to a local album-art image file, or nothing
#                          if the current track has none (popup image row;
#                          downloads+caches remote art URLs via curl)
#   media.sh prev / playpause / next -> playerctl actions (popup buttons)
#   media.sh menu       -> popup definition, read once at startup (see
#                          README, "Module-declared menus")
mode="${1:-text}"

track() {
	playerctl metadata --format '{{artist}} - {{title}}' 2>/dev/null
}

case "$mode" in
menu)
	self="$0"
	echo 'popup : hover : buttons'
	echo "popup_image : \"$self art\""
	echo "popup_info : \"$self track\""
	echo "popup_buttons : \"\" : \"$self prev\" : \"\" : \"$self playpause\" : \"\" : \"$self next\""
	;;
track)
	track
	;;
art)
	url=$(playerctl metadata mpris:artUrl 2>/dev/null)
	case "$url" in
	file://*)
		path="${url#file://}"
		[ -f "$path" ] && printf '%s' "$path"
		;;
	http://*|https://*)
		cache="${XDG_CACHE_HOME:-$HOME/.cache}/sxbar-media-art"
		mkdir -p "$cache" 2>/dev/null
		hash=$(printf '%s' "$url" | cksum | awk '{print $1}')
		file="$cache/$hash"
		if [ ! -s "$file" ] && command -v curl >/dev/null 2>&1; then
			curl -fsSL "$url" -o "$file" 2>/dev/null
		fi
		[ -s "$file" ] && printf '%s' "$file"
		;;
	esac
	;;
prev)
	playerctl previous 2>/dev/null
	;;
playpause)
	playerctl play-pause 2>/dev/null
	;;
next)
	playerctl next 2>/dev/null
	;;
*)
	st=$(playerctl status 2>/dev/null)
	case "$st" in
	Playing) glyph=' > ' ;;
	Paused)  glyph=' || ' ;;
	*)       exit 0 ;;
	esac
	printf '%s%s\n' "$glyph" "$(track)"
	;;
esac
