#!/bin/bash

################################################
#Purpose: Automate the downloading of files from rapidshare using the free account 
#using simple unix tools.
#Date: 14-7-2008
#Authors: Slith, Tune, Itay
#Improvements, Feedback, comments: Please go to http://emkay.unpointless.com/Blog/?p=63
#Notes: To use curl instead of wget use 'curl -s' and 'curl -s -d'
#Version: 1.?
################################################

#IMPORTANT! - PLEASE SHARE ALL IMPOROVEMENTS MADE.

#Thanks to Tune for getting rid of the curl dependency, extracting the correct wait time and
#makeing it work with file downloads other than .rar files.

#TODO: Make work concurrently with a list of proxys
#TODO: If possible resume partially downloaded files using another mirror / move to next mirror
#if the attempted mirror is down.

###

scriptdir=`dirname $0`
in=input.txt

timer()
{
    TIME=${1:-960}
	/bin/echo -ne "${2:-""}\033[s"
    for i in `seq $TIME -1 1`; do
        /bin/echo -ne "\033[u $(printf "%02d" `expr $i / 60`)m$(printf "%02d" `expr $i % 60`)s ${3:-""}"
        sleep 1
    done
    /bin/echo -ne "\033[u 00m00s"
    echo
}

while [ `wc -l $in | cut -d " " -f 1` != 0 ]; do
	read line < $in
	URL=$(wget -q -O - $line | grep "<form id=\"ff\" action=\"" | grep -o 'http://[^"]*');
	output=$(wget -q -O - --post-data "dl.start=Free" "$URL");
	
	# check if server is busy
	serverbusy=$(echo "$output" | egrep "Currently a lot of users are downloading files. Please try again in.*minutes" | grep -o "[0-9]*")
	if [ "$serverbusy" != "" ]; then
		timer `expr $serverbusy '*' 60` "Server busy. Waiting" "before retrying..."
		continue; # try again
	fi

	# check whether we need a long wait (between downloads) and how long
	longtime=$(echo "$output" | egrep "Or try again in about.*minutes" | egrep -o "[0-9]*")
	if [ "$longtime" != "" ]; then
		timer `expr '(' $longtime + 1 ')' '*' 60` "Waiting" "(free user limit) ..."
		URL=$(wget -q -O - $line | grep "<form id=\"ff\" action=\"" | grep -o 'http://[^"]*');
		output=$(wget -q -O - --post-data "dl.start=Free" "$URL");
	fi
	
	# check length of short wait (before download)
	time=$(echo "$output" | grep "var c=[0-9]*;" | grep -o "[0-9]\{1,3\}");

	time=$(echo "$time" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') # trim ws
	if [ "$time" = "" ]; then
		echo "Download of \"`basename "$line"`\" failed".
		echo $line >> fail.txt
		sed -i '1 d' $in; #remove line from input file
		continue
	fi
	ourfile=$(echo "$output" | grep "document.dlf.action=" | grep checked | grep -o "http://[^\\]*");
	timer $time "Waiting" "for download of `basename "$ourfile"`";
	if ! wget -c $ourfile; then
		echo 'Download failed. Retrying - looks like a temporary server issue.'
	else
		sed -i '1 d' $in; #remove line from input file
		$scriptdir/unpack.sh `basename "$line"` $in & # if it's a rar file, try to unpack
	fi
done

if [ -e fail.txt ]; then
	mv fail.txt $in # move failed downloads to input
fi

