#!/bin/bash
# 2/13/2021 long-cat.net
#
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004
#  
# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
# 
# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.
#  
#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
# 
#  0. You just DO WHAT THE FUCK YOU WANT TO.

# options parsing
SHORT=a:r:y:t:
LONG=album:,artist:,year:,trim:,help

PARSED=$(getopt --options $SHORT --longoptions $LONG --name "$0" -- "$@")
if [ "$?" -ne 0 ]; then
	exit 2
fi

eval set -- "$PARSED"

while true; do
	case "$1" in
		-a|--album)
			album="$2"
			shift 2
			;;
		-r|--artist)
			artist="$2"
			shift 2
			;;
		-y|--year)
			year="$2"
			shift 2
			;;
		-t|--trim)
			trim="$2"
			shift 2
			;;
		--help)
			echo "Usage: ytalbum [OPTION]... [PLAYLIST]"
			echo "Downloads a YouTube playlist, encodes to MP3, and sets metadata for an album"
			echo "WARNING: this will probably break things if you run it in a dir with existing media files"
			echo
			echo "-a, --album	Album title"
			echo "-r, --artist	Artist (sets artist AND album artist tags)"
			echo "-y, --year 	Release year"
			echo "-t, --trim	Trim text from the end of all titles"
			echo "    --help	Display this message"
			exit 0
			;;
		--)
			shift
			break
			;;
		*)
			echo $1
			echo "Programming error"
			exit 3
			;;
	esac
done

# handle input playlist
if [ "$#" -ne 1 ]; then
	echo "$0: A single input playlist is required."
	echo "ytalbum --help for usage"
	exit 1
fi

playlist="$1"

# download the videos
youtube-dl -f bestaudio -o "%(playlist_index)02d %(title)s.%(ext)s" "$playlist"

# encode to mp3 (LAME V0)
for f in *; do
	tn=`grep -Eo ^[0-9]+ <<< "$f"`
	fn=${f%.webm}
	fn=${fn%.m4a}
	fn=${fn%${trim}}
	title=${fn#$tn }
	# remove some crap from end of title
	title=${title%(Remastered)}
	ffmpeg -i "$f" \
		   -q 0 \
		   -compression_level 0 \
		   -metadata album="$album" \
		   -metadata artist="$artist" \
		   -metadata year="$year" \
		   -metadata title="$title" \
		   -metadata track="$tn" \
		   -metadata album_artist="$artist" \
		   -id3v2_version 3 \
		   "$fn.mp3"
	rm "$f"
done
