#!/usr/bin/env bash
# ytdl -- download a YouTube video using specific yt-dlp settings

. lib.bash || exit

usage() {
	echo "$progname [-B browser] [-O arg] [-n] [-p prefix] [-t start-end] <url>..."
	echo
	echo_opt "-B browser"	"have yt-dlp get cookies from specified browser"
	echo_opt "-t start-end"	"time range to download"
	echo_opt "-O arg"	"pass custom argument to yt-dlp"
	echo_opt "-n"		"add channel name as filename prefix"
	echo_opt "-p prefix"	"add custom filename prefix"
}

addchannel=0
fileext=""
extraargs=(--no-mtime)

args=$(getopt -n ${0##*/} -o B:O:np:xt: -l channel,help,prefix:,time: -- "$@") || exit
eval set -- "$args"

while (( $# )); do
	arg=$1; shift
	case $arg in
	-B)
		case $1 in
		f) extraargs+=(--cookies-from-browser firefox);;
		*) extraargs+=(--cookies-from-browser "$1");;
		esac; shift;;
	-O)
		extraargs+=("${1#,}"); shift;;
	-n|--channel)
		addchannel=1;;
	--help)
		usage; exit;;
	-p|--prefix)
		prefix=$1; shift;;
	-x)
		extraargs+=(-x);;
	-t|--time)
		extraargs+=(--download-sections "*$1"); shift;;
	--)
		break;;
	*)
		exit 2;;
	esac
done

if (( ! $# )); then
	die "no URLs specified"
fi

case ${0##*/} in
	ytdl-mp4-1080p)
		vh="[height<=1080]"
		vf="[vcodec^=avc1.][ext=mp4]"
		fileext="mp4"
		;;
	ytdl-mp4-720p)
		confirm "YouTube's 720p is now crap, use anyway?" || exec ytdl-mp4-1080p "$@"
		vh="[height<=720]"
		vf="[vcodec^=avc1.][ext=mp4]"
		fileext="mp4"
		;;
	ytdl-mp4-480p)
		vh="[height<=480]"
		vf="[vcodec^=avc1.][ext=mp4]"
		fileext="mp4"
		;;
	ytdl-mp4)
		vh=""
		vf="[vcodec^=avc1.][ext=mp4]"
		fileext="mp4"
		;;
	ytdl-mkv)
		#vh=""
		vh="[height<=1080]"
		vf="[ext=mp4]"
		fileext="mkv"
		extraargs+=(
			--sub-format "ass/srt/best" \
			--convert-subs "ass" \
		)
		;;
	*)
		# Continue anyway, for other websites which don't work with the YT-specific vh/vf.
		;;
esac

if [[ $vh || $vf ]]; then
	f="bestvideo${vh}${vf}+bestaudio[ext=m4a]/bestvideo${vh}+bestaudio"
	extraargs+=(--format "$f")
fi

if [[ $fileext ]]; then
	extraargs+=(--merge-output-format "$fileext")
fi

name="${prefix% -}${prefix+ - }%(title)s [%(id)s].%(ext)s"
if (( addchannel )); then
	name="%(channel)s - $name"
fi

do: yt-dlp \
	--console-title \
	--add-metadata \
	--embed-subs \
	--sub-langs "all,-live_chat" \
	--output "$name" \
	--windows-filenames \
	"${extraargs[@]}" \
	"$@"
