#!/bin/bash
die() {
    echo "$0: $*">&2
    exit 1
}
cleanup() {
    [ -n "$tmp" ] && rm -f "$tmp"
}
set -e
if [ $# -ne 1 ]; then
    echo "Usage: $0 <URL>" >&2
    exit 1
fi
tmp=
trap cleanup EXIT
tmp=$(mktemp -t $(basename $0).XXXXXX) || die mktemp failed
 
outfile=
 
end=false
while [ $# -gt 0 ]; do
    case "$1" in
        -o) outfile="$2"; shift; shift;;
        --) end=true;;
        -*) die invalid option;;
        *) end=true;;
    esac
    $end && break
done
 
URL="$1"
 
echo -n "Getting video information... "
curl -s -f -o "$tmp" "$URL"
if [ -z "$outfile" ]; then
    title=$(perl -ne '
    if (m,<title>youtube - (.*)</title>,i) {
        $_ = $1;
        s/[^a-z0-9\-]/_/gi;
        print;
        exit;
    }' < "$tmp")
    [ -z "$title" ] && die could not figure out the title
    outfile="$title.mpg"
fi
echo "\"${title}\""
[ -e "$outfile" ] && die output file "$outfile" exists already
 
PARAM=$(perl -ne '
if (m,player2.swf\?(.*?)",) {
    print $1;
    exit
}' < "$tmp")
[ -z "$PARAM" ] && die could not figure out url to get flv
 
echo -n "Downloading video... "
curl -s -fL -e "$URL" -o "$tmp" "http://youtube.com/get_video.php?$PARAM"
echo "done (`ls -sh $tmp | sed -e 's/ .*$//'` flv file received)"
 
echo -n "Transcoding... "
ffmpeg -i "$tmp" -r 30 -ab 64 -ar 22050 -b 500 -s 320x240 "$outfile" &> /dev/null
echo "done."
 
ls -sh "$outfile"

