#!/bin/sh
set -eu
set -x

QUEUE="$HOME/archive/vid/queue.txt"
DB="$HOME/archive/vid/metadata-database.txt"

LIST="$(mktemp)"
touch "$DB"
while IFS='' read -r url; do
  MATCH="$(grep -F "$url" "$DB" ||:)"
  if [ -n "$MATCH" ]; then
    echo "$MATCH" >> "$LIST"
  else
    printf '%s - %s\n' "$(youtube-dl "$url" -o '%(title)s - %(uploader)s' --get-filename)" "$url" >> "$DB" &
    echo "$url" >> "$LIST"
  fi
done < "$QUEUE"

file_and_stuff="$(dmenu -l 20 -p 'Media: ' < "$LIST")"

if [ -n "$file_and_stuff" ]; then
  file="$(echo "$file_and_stuff" | awk -F' - ' '{print $NF}')"
  "$HOME/dev/libre/dotfiles/scripts/vid" "$file"
fi
