#!/bin/bash
#
# Piotr Jachacy
# jachacy@gmail.com
#
# ostatnia modyfikacja: 13.10.2009
#
# /* This program is free software. It comes without any warranty, to
# * the extent permitted by applicable law. You can redistribute it
# * and/or modify it under the terms of the Do What The Fuck You Want
# * To Public License, Version 2, as published by Sam Hocevar. See
# * http://sam.zoy.org/wtfpl/COPYING for more details. */ 
#

function odliczanie
{
	x=$1
	while [ $x -ge 1 ]; do
		printf "\r%-5s" $x"s"
		x=$[x -1]
		sleep "1"
	done
	printf "\r%-5s" ""
}


function pobierz
{
	link=$1

	link=$(wget "$link" -q -O - | grep 'form id="ff"' | sed -e 's/.*action="\(.*\)"\s.*/\1/')

	if [ -n "$link" ] 
	then
		link=$(wget --post-data "dl.start=Free" $link -q -O -)


		if [  -n "$(echo "$link" | grep "Please wait until the download is completed")" ]
		then
			echo "Sciągasz inne pliki."
			exit
		elif [  -n "$(echo "$link" | grep "You have reached the download limit for free-users. Would you like more?")" ]
		then
			minuty=$(echo "$link" | grep "Instant download access! Or try again in about" | sed -e "s/.*about \([0-9]*\) minutes.*/\1/")
			echo "Przekroczyłeś limit ściagania, musisz odczekać około $minuty minut"
			
			minuty=$[$minuty*60+30]	
			
			odliczanie $minuty
			
			pobierz $1
		elif [ -n "$(echo "$link" | grep "Currently a lot of users are downloading files.")" ]
		then
			minuty=$(echo "$link" | grep "Please try again in" | sed -e "s/.*in \([0-9]*\) minutes.*/\1/")

			echo "Serwer jest przeciążony. Musisz odczekać około $minuty minut"

			minuty=$[$minuty*60+30]

			odliczanie $minuty

			pobierz $1
		elif [ -n "$(echo "$link" | grep "We regret that currently we have no available slots for free users.")" ]
		then
			minuty=$(echo "$link" | grep "Unfortunately you will have to wait" | sed -e "s/.*wait \([0-9]*\) minutes.*/\1/")
			echo "Brak wolnych slotów dla użytkowników darmowych. Musisz odczekać około $minuty minut"

			minuty=$[$minuty*60+30]

			odliczanie $minuty

			pobierz $1
		else
			czas=$(echo "$link" | grep "var c" | sed -e "s/var c=\([0-9]*\);.*/\1/")

			odliczanie $czas

			link=$(echo "$link" | grep 'form name="dlf"'| sed -e 's/.*action="\(.*\)"\s.*/\1/')
			wget --post-data "mirror=on" "$link"		
		fi	
					
	else
		echo -e "Nie udało się pobrać pliku: \n\t$1"
	fi


}

if [ "$1" = "-i" ] && [ -n "$2" ]
then
	for x in $(cat $2)
	do
		if [ -n "$x" ]
		then
			pobierz "$x"
		fi
	done
	
elif [ "$1" = "--help" ] || [ "$1" = "-h" ]
then
	echo -e "Użycie: rsget.sh [OPCJE]... [URL]...\n"
	echo -e "\t--help\t\t\twyświetla pomoc"
	echo -e "\t-i ListaPlikow\t\tpobiera pliki z listy\n"
	
elif [ -n "$1" ]
then
	pobierz "$1"
	
fi

