#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  yt [-f] [-n PLAYLIST_COUNT] [URL...|FILE...|-]
		  yt -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -n PLAYLIST_COUNT    the number of videos to grab from a
		                       playlist (default: 15)
		  -f                   force to download a video already in the
		                       archive
		  -h, --help           show this message

		  URL                  an 'https://...' address
		  FILE                 a file with 'https://...' addresses, one
		                       per line


		Download videos and store them locally.


		Examples:

		  Download the video from the given URL:

		    $ yt https://www.youtube.com/watch?v=EihZv2XgJdU


		  Force re-download the latest 5 videos already downloaded:

		    $ yt -nf5 https://www.youtube.com/watch?list=TLPQMTIwODIwMjLnL2XjyRRgSw
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

PLAYLIST_COUNT=15
while getopts 'fn:h' flag; do
	case "$flag" in
		(f)
			FORCE=1
			;;
		(n)
			PLAYLIST_COUNT="$OPTARG"
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))
set -x

if [ -z "${1:-}" ]; then
	echo 'Missing URL|FILE argument' >&2
	usage >&2
	exit 2
fi


if [ ! -e "$1" ]; then
	F="$(mkstemp)"
	trap 'rm -f "$F"' EXIT
	printf '%s\n' "$1" > "$F"
else
	F="$1"
fi


YT_TEMPLATE="$HOME/Downloads/yt-dl/%(uploader)s/%(upload_date)s %(title)s.%(ext)s"

EXTRA_OPTIONS=''
if [ -z "${FORCE:-}" ]; then
	EXTRA_OPTIONS="--download-archive $HOME/Documents/yt-dl-seen.txt"
fi

# The value of $EXTRA_OPTIONS doesn't depend on user input, and can't contain
# spaces, unless $HOME contains spaces:
# shellcheck disable=2086
yt-dlp \
	--batch-file "$F"                \
	--prefer-free-formats            \
	--playlist-end "$PLAYLIST_COUNT" \
	--write-description              \
	--output "$YT_TEMPLATE"          \
	$EXTRA_OPTIONS
