#!/usr/bin/env bash

url=$1

album=$(yt-dlp -I 1:1 --skip-download --print "%(album)s" ${url})
artist=$(yt-dlp -I 1:1 --skip-download --print "%(artists.0,artist)s" ${url})
folder="${artist} - ${album}"

yt-dlp \
	--embed-metadata \
	--parse-metadata "%(playlist_index)s:%(track_number)s" \
	--parse-metadata "%(release_date,upload_date)s:%(date)s" \
	--parse-metadata "%(artists.0,artist)s:%(artist)s" \
	--extract-audio --audio-format opus \
	-o "${folder}/%(playlist_index)s - %(title)s.%(ext)s" ${url}

yt-dlp -I 1:0 --write-thumbnail -o "${folder}/cover.jpg" ${url}

cd "${folder}"

for file in *.opus; do
	ffmpeg \
		-hide_banner \
		-i "${file}" -i "cover.jpg" \
		-map_metadata 0:s:a:0 -disposition attached_pic \
		-c:a copy "0${file}"

	rm "$file"
	mv "0${file}" "${file#"0"}"
done
