#!/usr/bin/env bash
set -Eeuo pipefail

# Always downloads video, doesn't look at the download-archive

URL_OR_PATH="${1:-}"
[[ -z "${URL_OR_PATH}" ]] && {
  echo 'Input "$URL_OR_PATH" is undefined.' > /dev/stderr
  exit 2
}

if [[ -f "${URL_OR_PATH}" ]]; then
  echo "File '${URL_OR_PATH}' exists, loading URLs from it..." > /dev/stderr
  youtube-dl --batch-file "${URL_OR_PATH}" \
             --format best                 \
             --output "${YT_TEMPLATE}"     \
             --write-description           \
             1>&2
  FILES="$(youtube-dl --batch-file "${URL_OR_PATH}" \
                     --output "${YT_TEMPLATE}"      \
                      --format best                 \
                     --get-filename)"
else
  echo "File '${URL_OR_PATH}' doesn't exist, treating it as an URL..." > /dev/stderr
  youtube-dl "${URL_OR_PATH}"          \
             --output "${YT_TEMPLATE}" \
             --format best             \
             --write-description       \
             1>&2
  FILES="$(youtube-dl "${URL_OR_PATH}"         \
                     --output "${YT_TEMPLATE}" \
                     --format best             \
                     --get-filename)"
fi

# if [[ ! -z "${VLC:-}" ]]; then
while IFS=$'\n' read -r file; do
  vlc "${file}"
  blue "Enqueued ${file} in VLC."
done <<<"${FILES}"
# fi
