#!/bin/bash

tmp_dir="$HOME/.cache/eww/music-art"
art_path=$tmp_dir/temp.png
art_blur_path="$tmp_dir/temp-blur.png"
cache_path="$tmp_dir/cache.conf"
cache_blur_path="$tmp_dir/cache-blur.conf"
log_path="$tmp_dir/log.txt"
default_path="$HOME/.config/eww/Main/images/default-music.svg"
default_blur_path="$HOME/.config/eww/Main/images/default-music-blur.png"

mkdir -p "$tmp_dir"

artlink="$(playerctl metadata mpris:artUrl)"
[ -f "$cache_path" ] && . "$cache_path"

# avoid unnecessary downloads
if [ -z "$artlink" ]; then
	art_path="$default_path"
	art_blur_path="$default_blur_path"
elif [[ "$cachedlink" != "$artlink" ]]; then
	echo "cachedlink=\"$artlink\"" > "$cache_path"
	echo "Updating music art: $artlink" >> "$log_path"

	if [[ "$artlink" == "file://"* ]]; then
		# Handle local file URLs
		local_file_path="${artlink#file://}"
		if [[ -f "$local_file_path" ]]; then
			magick "$local_file_path" "$art_path" || exit 1
		fi
		magick "$art_path" -blur 0x8 "$art_blur_path"
	elif [[ "$artlink" =~ ^https?:// ]]; then
		# Handle HTTP/HTTPS URLs
		curl -s "$artlink" --output "$art_path"_orig || exit 1
		magick "$art_path"_orig "$art_path" || exit 1
		magick "$art_path" -blur 0x8 "$art_blur_path"
	else
		echo "Unknown art link format: $artlink" >> "$log_path"
		art_path="$default_path"
		art_blur_path="$default_blur_path"
	fi
fi

echo "path=\"$art_blur_path\"" > "$cache_blur_path"
echo "$art_path"