#!/bin/bash

#
# fix free slot/flood warning wait time
#

echo "

			*****************************
			**         Qoobster        **
			**         v 2.2.2         **
			**   s6052@pjwstk.edu.pl   **
 			*****************************


"

# number of download attempts
ATTEMPTS=3


# function runs automatically after each successful download
# file's url being param
# remember that each function must have at least one command
function afterSuccessfulDownloadingFile() {

true
}



# function runs automatically after each failed download
# file's url being param
# remember that each function must have at least one command
function afterFailedDownloadingFile() {
echo "skip $1" >> skipped.txt

true
}


# function runs automatically in the end of the Qoobster
# list of urls is a param
# remember that each function must have at least one command
ALL=$@
function afterAll() {

true
}


while  [ $# -ne 0 ] ;
do	 	

	FILE=$1

	NAME=`echo $FILE | cut -d'/' -f6`
	NR=`echo $FILE | cut -d'/' -f5`

	echo -e " - file:\n$FILE"

	WAIT=1
	CURENTATEMPT=$ATTEMPTS
		while [ $WAIT -eq 1 ];
		do
		RESPONSE=`wget -q -O- "http://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=download_v1&fileid=$NR&filename=$NAME&try=1&cbf=RSAPIDispatcher&cbid=1"`

			if [ `echo $RESPONSE | grep "DL:" | wc -l` -ne 1 ] ; then 
			
				if [ $[ CURENTATEMPT - 1 ] -eq -1 ] ; then 
				afterFailedDownloadingFile $FILE
				shift
				continue 2
				fi
			
			
			TIME=`echo $RESPONSE | cut -d" " -f5`
				# test czy integer
				if ! [ "$TIME" -eq "$TIME" &>/dev/null ]; then
				TIME=300 #czekanie na zwolninie slotu lub flood warning, api nie daje info ile trza czekac ofc
				fi
				
				i=0
				for (( i=1; i<=$TIME; i++ ))
				do
				sleep 1
				echo -e -n "\r - zajete czekam "$[ TIME - $i ]"s   "	
				done
			echo ""
			else
			WAIT=0
			fi
		done


	SERVER=`echo $RESPONSE | cut -d":" -f2 | cut -d"," -f1`
	AUTH=`echo $RESPONSE | cut -d":" -f2 | cut -d"," -f2`
	TIME=`echo $RESPONSE | cut -d":" -f2 | cut -d"," -f3`

		i=0
		for (( i=1; i<=$TIME; i++ ))
		do
		sleep 1
		echo -e -n "\r - czekam "$[ TIME - $i ]"s   "	
		done

	wget -O$NAME 'http://'$SERVER'/cgi-bin/rsapi.cgi?sub=download_v1&editparentlocation=0&bin=1&fileid='$NR'&filename='$NAME'&dlauth='$AUTH
	afterSuccessfulDownloadingFile $FILE
	shift
done

afterAll $ALL
