#!/bin/sh
#
# ys - perform a search on youtube and return the best result (title + link)
#
# ---
# source: https://git.z3bra.org/scripts/files.html

usage() {
  echo "$(basename "$0") [-htu] [-n <num>] <query>"

  test -z "$1" && return

  cat <<EOF
        -h : display this help
        -t : output titles only (default 'title - uri')
        -u : output uris only
        -n : print only <num> results (default: 3)
EOF
}

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}"

# shellcheck disable=SC2250
curl -s "${url}" | sed -n "s,$regex,$output,p" | sed "${num}"q
