#!/bin/sh
set -eu

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

help() {
	cat <<-'EOF'

	Options:
	  -f            force to download a video already
			in the archive
	  -h, --help    show this message
EOF
}

mkstemp() {
	echo 'mkstemp(template)' | m4 -D template="${TMPDIR:-/tmp}/m4-tmpname."
}


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

while getopts 'fh:' flag; do
	case "$flag" in
		f)
			FORCE=1
			;;
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

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


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


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

if [ -z "${FORCE:-}" ]; then
	ARCHIVE_OPTION="--download-archive $HOME/archive/youtube-dl-seen.conf"
fi

youtube-dl \
	--batch-file "$F"                            \
	--format best                                \
	--prefer-free-formats                        \
	--playlist-end "${2:-$DEFAULT_PLAYLIST_END}" \
	--write-description                          \
	--output "$YT_TEMPLATE"                      \
	${ARCHIVE_OPTION:-}
