#!/bin/bash


##################################################
usage()  {


cat <<EOL
YOUTUBE VIDEO DOWNLOADER

Written by Alberto Garcia <agarcia-at-igalia-com>
Modifications by:
Added ffmepg convertion: ArathornX <arathornx@gmail.com> 
Added parameter options: Sebastian Emilio Narvaez <snarvaezsoft-at-gmail.com>"

USAGE:
   youtube.sh [options] http://www.youtube.com/watch?v=<video_ID>
 or
   youtube.sh [options] <video_ID>

OPTIONS:

-l amount
    Limit the download speed to amount bytes per second. Amount may be expressed in bytes, kilobytes with the k suffix, or megabytes with the m suffix. For example, -l 20k will limit the retrieval rate to 20KB/s. This is useful when, for whatever reason, you don't want Wget to consume the entire available bandwidth.

-v 
    Be verbose
-o 
    Set ouput name.  For example -o house  will convert to a file named
house.avi  or   house.mpeg  depending on the choosen format.

EXAMPLE:

 ./youtube.sh -v -l 20k -o octopus_escape -f avi http://www.youtube.com/watch?v=SCAIedFgdY0


EOL

exit 1

}



##################################################

VALIDFORMATS='avi|mpeg'


FORMAT=mpeg  # default
VERBOSE=
LIMITRATE=

while getopts f:l:vo: options
do

  case $options in

    f)
    FORMAT=$OPTARG    # el formato (extension) a convertir: avi, mpeg
    ;;

    v)
    VERBOSE='v'        # mensajes extra  
    ;;

    o)
    OUTPUT=$OPTARG   # el nombre del archivo convertido final
    ;;

    l)
    LIMITRATE="--limit-rate=$OPTARG"
    ;;

    ?)
    echo "opcion requiere argumento"
    usage
    exit 1
    ;;

    *)
    echo opcion desconocida: $options
    usage
    exit 1
  esac
done


#check if valid format
case $FORMAT in

    avi|mpeg)
    #ok, do nothing
    ;;

    *)
    #catch anything else, is wrong
    echo "$FORMAT no es un formato valido. Por favor con la opcion -f utilice alguno de estos: $VALIDFORMATS"
    usage
    exit 1
    ;;
esac


shift $(($OPTIND - 1))
#  Decrements the argument pointer so it points to next argument.
#  $1 now references the first non option item supplied on the command line
#+ if one exists.



VID="$1"

if ! [ "$VID" ]; then
    echo "Error: falta el parametro IdVideo";
    usage
    exit 1
fi 



if ! [ "$OUTPUT" ] 
then
    OUTPUT="$VID"
fi



##################################################

echo "$1"

VID=$(echo "$1"|sed "s/.*v=\([^&]*\).*/\1/")
URL1="http://www.youtube.com/watch?v=$VID"
echo -n "Getting $URL1 ..."
PARAM="$(wget -q -O - "$URL1"|grep watch_fullscreen|cut -d '&' -f 3)"
echo " done."
URL2="http://www.youtube.com/get_video?video_id=$VID&$PARAM"
echo -n "Getting $URL2 ..."
URL3="$(wget -S "$URL2" 2>&1|sed -n /Location:/s/.*http:/http:/p)"
echo " done."

echo "Video address is $URL3"


wget "$VERBOSE" "$LIMITRATE"  -O "$VID".flv "$URL3"


ffmpeg -i "$VID".flv "$OUTPUT"."$FORMAT"  &&  echo "DONE" && echo "$OUTPUT"."$FORMAT"




