# Author: Theodore Zacharia
# V0.1: 30/07/2021 - Initial Release
#
# youtubedlb - YoutubeDownloadBest !
# This script provides some support to download high quality youtube videos
# when there is only a non-audio version of the video in a higher quality
# than the audio included version (that seems to happen a lot)
#
# Uses the excellent youtube-dl to do the actual work
#

# *** Globals
TRACE=0
MKV_MODE=0
MYARG=""


# *** Functions
_usage()
{
	echo "usage: $0 [-h] [-t] [-m] [-l] youtube_url"
	echo "where"
	cat <<- _EOF_
  -h        Displays this help message
  -t        Set trace on
  -l        List formats available for the video
  -m        Specifically try to get an mkv file, default is any format
_EOF_
}

_youtube-dl_video_and_audio_best_no_mkv_merge ()
{
  if [ $TRACE -eq 1 ] ; then echo "called _youtube-dl_video_and_audio_best_no_mkv_merge" ; fi
  video_type=$(youtube-dl -F "$@" | grep "video only" | awk '{print $2}' | tail -n 1)
  case $video_type in
    mp4)
      youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]' "$@";;
    webm)
      youtube-dl -f 'bestvideo[ext=webm]+bestaudio[ext=webm]' "$@";;
    *)
      echo "new best videoformat detected, please check it out! -> aborted";;
  esac
}

_youtube-dl_mkv ()
{
  if [ $TRACE -eq 1 ] ; then echo "called _youtube-dl_mkv" ; fi
  youtube-dl -f 137+bestaudio --merge-output-format mkv $@
}


# *** Mainline

# process input parameters
while getopts thml AOPT
do
case $AOPT in
	t) TRACE=1 ;; # set TRACE mode
  m) MKV_MODE=1 ;;
  l) youtube-dl --list-formats $@
     exit $? ;;
	h) _usage
	   exit 1 ;;
	*) echo "$AOPT is an invalid option" >&2
	   exit 2 ;;
esac
done

shift $((OPTIND-1))

if [ $MKV_MODE -eq 1 ]
then
	_youtube-dl_mkv $@
else
	_youtube-dl_video_and_audio_best_no_mkv_merge $@
fi
