#!/bin/sh

query_artist="$(playerctl -i firefox metadata --format '{{ artist }}')"
query_title="$(playerctl -i firefox metadata --format '{{ title }}')"
query="$query_artist - $query_title"

tmpdir="$(mktemp -d)"

echo "Searching YouTube for:"
echo "  $query"
echo

yt-dlp "ytsearch1:$query" \
  --print "━━━━━━━━━━━━━━━━━━━━━━━" \
  --print "Title:     %(title)s" \
  --print "Channel:   %(uploader)s" \
  --print "Duration:  %(duration_string)s" \
  --print "URL:       %(webpage_url)s" \
  --print "━━━━━━━━━━━━━━━━━━━━━━━"

echo
read -p "Download this? [y/N] " confirm

if [[ "$confirm" =~ ^[Yy]$ ]]; then
    yt-dlp -x --audio-format m4a -f bestaudio \
        "ytsearch1:$query" \
	--embed-metadata \
	-o "$tmpdir/%(artist)s - %(albums)s - %(title)s.%(ext)s"

    file="$(ls "$tmpdir"/* 2>/dev/null | head -n1)"

    if [[ -n "$file" ]]; then
        beet import --from-scratch "$file"
    else
        echo "Download failed. Even chaos has limits."
    fi

    rm -rf "$tmpdir"
else
    echo "Aborted."
fi

read -n 1 -s -r -p "Done. Press any key to close."
