#!/bin/sh
#
# ydl - download audio track of the first result of a youtube search
# and add it to MPD library (will end up with a .mp3, for tags)

usage() {
  echo "$(basename "$0") [-h] <query>"
}

ys() {
  num=3
  regex='^.*<a href="\(/watch[^"]*\)"[^>]*>\([^<]*\)</a>.*$'
  output='\2 - http://youtube.com\1'

  while getopts "hn:tu" OPT; do
    case ${OPT} in
      n) num=${OPTARG};;
      t) output='\2';;
      u) output='http://youtube.com\1';;
      h) usage long; exit 0;;
      *) usage; exit 1;;
    esac
  done

  shift "$((OPTIND - 1))"

  query=$(echo "$@" | tr ' ' '+')
  # url="https://www.youtube.com/results?search_query=${query}"
  url="https://www.youtube.com/results?search_query=${query}"

  curl -s "${url}" | sed -n "s,${regex},${output},p" | sed "${num}"q
}

# don't process if no argument given
test $# -eq 0 && usage && exit 1

# you can either pass MULTIPLE search terms or a SINGLE url
test $# -gt 1 && uri=$(ys -n1 -u "$@") || uri="$1"

# give up if we got no uri
if test -z "${uri}"; then
  echo "no result found"
  exit 1
fi

# download and extract audio track
# youtube-dl -q -x --audio-format mp3 -o '%(title)s.%(ext)s' "${uri}"
yt-dlp --quiet --extract-audio --audio-format mp3 --output '%(title)s.%(ext)s' "${uri}"

exit 0
