#!/bin/sh tmpdir="$(mktemp -d)" monitor="$(pactl get-default-sink).monitor" echo "Listening on $monitor (Shazam)..." result="$(songrec recognize -d "$monitor" -j)" artist="$(printf '%s' "$result" | jq -r '.track.subtitle // empty')" title="$(printf '%s' "$result" | jq -r '.track.title // empty')" album="$(printf '%s' "$result" | jq -r '[.track.sections[]? | select(.type=="SONG") | .metadata[]? | select(.title=="Album") | .text] | first // empty')" year="$(printf '%s' "$result" | jq -r '[.track.sections[]? | select(.type=="SONG") | .metadata[]? | select(.title=="Released") | .text] | first // empty')" genre="$(printf '%s' "$result" | jq -r '.track.genres.primary // empty')" if [ -z "$artist" ] || [ -z "$title" ]; then echo "Could not identify song. Even chaos has limits." rm -rf "$tmpdir" exit 1 fi query="$artist - $title" echo echo "Identified: $query" echo 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" \ -o "$tmpdir/download.%(ext)s" file="$(ls "$tmpdir"/download.* 2>/dev/null | head -n1)" if [[ -n "$file" ]]; then script_dir="$(cd "$(dirname "$0")" && pwd)" "$script_dir/retag" "$tmpdir" --commit --no-backup tag_artist="$(ffprobe -v error -show_entries format_tags=artist -of default=nw=1:nk=1 "$file")" tag_album="$(ffprobe -v error -show_entries format_tags=album -of default=nw=1:nk=1 "$file")" tag_title="$(ffprobe -v error -show_entries format_tags=title -of default=nw=1:nk=1 "$file")" if [[ -z "$tag_artist" && -z "$tag_title" ]]; then echo "retag found nothing — falling back to songrec tags." tagged="$tmpdir/tagged.${file##*.}" ff_args=(-y -i "$file" -c copy -metadata artist="$artist" -metadata title="$title") [[ -n "$album" ]] && ff_args+=(-metadata album="$album") [[ -n "$year" ]] && ff_args+=(-metadata date="$year") [[ -n "$genre" ]] && ff_args+=(-metadata genre="$genre") if ffmpeg "${ff_args[@]}" "$tagged" >/dev/null 2>&1; then mv "$tagged" "$file" tag_artist="$artist" tag_album="$album" tag_title="$title" fi fi a="${tag_artist:-$artist}" b="${tag_album:-${album:-Unknown Album}}" t="${tag_title:-$title}" # filesystem-safe: replace path separator a="${a//\//_}" b="${b//\//_}" t="${t//\//_}" dest="$HOME/Music/$a/$b" mkdir -p "$dest" mv "$file" "$dest/$t.m4a" echo "Saved to: $dest/$t.m4a" else echo "Download failed. Even chaos has limits." fi rm -rf "$tmpdir" else rm -rf "$tmpdir" echo "Aborted." fi read -n 1 -s -r -p "Done. Press any key to close."