#!/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
#Improvements: Please email them to jwhatson@gmail.com
#Post Feedback and comments to http://emkay.unpointless.com/Blog/?p=63
#Notes: To use curl instead of wget use 'curl -s' and 'curl -s -d'
#Version: 1.2 - Rapidshare has added a wait time in between file downloads. On top of your download
#to start. This has been fixed.
#Added a 'kill time' feature. Specify killTime as an hour of the day and if the time is greater than this. 
#the script will end. Useful for using cron to start script at offpeak time and killing it when off speak ends. 
################################################

mirror=dt.rapidshare.com;

## possible mirrors
# cg.rapidshare.com
# l34.rapidshare.com
# tg.rapidshare.com
# gc2.rapidshare.com
# dt.rapidshare.com
# tl2.rapidshare.com
# l32.rapidshare.com
# l3.rapidshare.com
# gc.rapidshare.com
# l33.rapidshare.com
# tl.rapidshare.com
# cg2.rapidshare.com

killTimeEnable=0
killTime=9

function getOutputFromFreeUserSubmit(){
        URL=$(wget -q -O - $line | grep "<form id=\"ff\" action=\"" | grep -o 'http://[^"]*');
        output=$(wget -q -O - --post-data "dl.start=Free" "$URL");
}

while read line
do

	if [[ $killTimeEnable -eq 1 && $(date +%H) -gt $killTime ]]; then exit; fi;

	getOutputFromFreeUserSubmit output; #call getOutputFromFreeUserSubmit, result is stored in $output
	posibleWaitTime=$(echo "$output" | grep "try again in about" | grep -o "[0-9]\{1,3\}");
	
	if [ -z "$posibleWaitTime" ]; then #check for zero lenght string
		echo "No wait time, likely to be the first file you have downloaded in a while";
	else
		echo "Waiting $[ $posibleWaitTime+1] minutes (in between file download wait)";
		sleep $[ $posibleWaitTime+1]m;
		getOutputFromFreeUserSubmit output; #Now we have waited we will try again...
	fi
	
	time=$(echo "$output" | grep "var c=[0-9]*;" | grep -o "[0-9]\{1,3\}");
	ourfile=$(echo "$output" | grep "document.dlf.action=" | grep -o "http://[^\"]*$mirror[^\\]*");
	echo "Waiting $time secs for download of $ourfile";
	sleep $time;
	wget $ourfile;

done < input.txt



