#!/bin/bash

# Author: Paul Kocialkowski
# Copyright: GNU General Public License
# Date: 27/08/2010
# Requires: sed, grep, wget, rtmpdump
# Version: 0.1

# Check arguments count
if (( $# < 1 ))
then
	echo "Usage: $0 <URL1> <URL2>..."
	exit
fi

i=0

# Loop to parse each argument
while (( $i <= $# ))
do
	# Get the ID
	rutube_id=$( echo $1 | sed "s/.*tracks\/\(.*\).html.*/\1/g" )
	
	# Get the video ID from URL
	rutube_video_id=$( echo $1 | grep "v=" | sed "s/.*?v=\([^&]*\).*/\1/g" )

	# If the video id is not in the URL, download the page and get it
	if [ "$rutube_video_id" = "" ]
	then
		rutube_video_id=$( wget $1 -O /dev/stdout -o /dev/null | grep '<EMBED src="http://video.rutube.ru/' | uniq | tr -cd '\40-\176' | sed "s/.*src=\"http:\/\/video.rutube.ru\/\([^\"]*\)\".*/\1/g" )
	fi

	# Get the video location
	rutube_video=$( wget http://bl.rutube.ru/$rutube_video_id.xml --cookies=on -O /dev/stdout -o /dev/null | grep CDATA | sed "s/.*<\!\[CDATA\[\(.*\)\]\].*/\1/g" )

	# Check if RTMP is used
	rutube_rtmp=$( echo $rutube_video | grep rtmp )

	# Now, let's download the video !
	if [ "$rutube_rtmp" = "" ]
	then
		wget --cookies=on "$rutube_video" -O "rutube_$rutube_id.flv"
	else
		rtmpdump -r "$rutube_video" -s "http://rutube.ru/player.swf" -o "rutube_$rutube_id.mp4"
	fi

	let i=1+$i
	shift
done


