#!/bin/sh

#  Yet Another YouTube Video Downloader and Encoder
#
# prerequisities: wget (everyone should have it)
#                 ffmpeg (http://ffmpeg.mplayerhq.hu/)
#
# Licensed under the NWL - No Whining License.
#
# You may use this, modify this, redistribute this provided you agree to:
# - not whine about it;
# - the fact that there is no warranty of any kind.
# - retain this copyright in full.
#
# Written by Anicka Bernathova <anicka@anicka.net> in 2007
# Updated by Pavel Dufek <pavel.dufek@tpc.cz> in 2008

usage()
{
cat <<EOW
Usage: youtube [-n video_name] [-d directory] url 
EOW
}

while getopts ":d:n:h" options; do
  case $options in
    d ) cd "$OPTARG";;
    n ) NAME="$OPTARG";;
    h ) usage ; exit 0 ;;
    ? ) usage ; exit 1 ;;
    * ) usage ; exit 1 ;;
  esac
done

shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	usage	
	exit 0
fi

if [ -z "$NAME" ]; then
	NAME=youtube_video
fi

URL=$1
BASE="http://youtube.com/get_video?"
tmp=`mktemp /tmp/youtube.XXXX` || exit 1

VIDEO=`wget -O - $URL | grep 'watch_fullscreen' | sed "s/.*\(video_id.\+\)&title.*/\1/"`
# Orig. Anicka and PD tried to use fixed number of params for fetching args
# in <video_id,title) ... 
# But it looks that there is a variable count of params before video_id (:
# So instead of cut -d? -f2 | cut -d\& -f3-8` we use Crouse's regexp sed ...
#echo "URL is $VIDEO."
#exit 1
if [ -z "$VIDEO" ]; then
	echo "Bad URL" >&2
	exit 1
fi
#rm $src

FULL=${BASE}${VIDEO}
echo "Time to take a nap: Downloading from $FULL"
wget -O $tmp $FULL

#exit 1

echo "Coffee break: Converting to mpeg... "
ffmpeg -i $tmp -s 320x240 "$NAME".mpg && rm $tmp
#ffmpeg -i $tmp -ab 56k -ar 22050 -b 500k -s 320x240 "$NAME".mpg && rm $tmp
# Simpler variant "-i file -s 320x240 outfile" works too, bitrates do not resample
#rm gmon.out

