#!/bin/bash

export MPD_HOST="$HOME/.mpd/socket"
DUNST_ID=$(sum <<<"mpd" | cut -d' ' -f1)

runtime="${XDG_RUNTIME_DIR}/i3blocks"
[[ ! -d "$runtime" ]] && mkdir -p "$runtime"

while true
do
	systemctl --user is-active mpd.service || exit 1
	timeout 5 mpc -w current
	onelineinfos="$(mpc -f '[%artist%§]%title%|[%file%]' current)"
	if [[ "$onelineinfos" != "$(<${runtime}/mpd)" ]]
	then
		echo "$onelineinfos" > ${runtime}/mpd
		echo "$(<${runtime}/mpd)                                         " > ${runtime}/mpd-scroll
		infos=$(mpc -f '[[%artist%\n]%title%[\n%album%]]|[%file%]' current)
		if [[ -z "$infos" ]]
		then
			infos="<i>Arrêt</i>"
		fi
		artist=$(sed -n 1p <<<$infos)
		title=$(sed -n 2p <<<$infos)
		album=$(sed -n 3p <<<$infos)
		[[ -z "$title" ]] && title="$artist" && artist=""
		title=$(basename "$title")
		curl -s -X POST -u breizh:$(pass show Web/pleroma.breizh.pm) \
			--data-urlencode "title=${title}" \
			--data-urlencode "artist=${artist}" \
			--data-urlencode "album=${album}" \
			https://pleroma.breizh.pm/api/v1/pleroma/scrobble &>/dev/null & 
		dunstify -r $DUNST_ID "MPD" "$infos"
		#( pidof cava && sleep 1 && pkill -USR1 cava ) &
	fi
done