#!/bin/bash

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details. 

# #################################################################

# This is just a simple wget script for downloading files 
# from www.uloz.to file hosting.
# 
# updated:  15.3.2012
#   email:  lobl.pavel@gmail.com

# #################################################################

# default download rate
rate='0'

# captcha, thisone is used all the time
captcha_user="RXkE"
captcha_nb="1"

# #################################################################

# display error 
error()
{
  echo -e "error: $1\n" >&2
}
 
# if user press ^C while wget is in subshell,
# we should kill it
# this will send terminate signal to all
# processes in this group
trap "{ echo; kill -15 -$$ ; }" SIGINT

printUsage()
{
  echo "$0 [OPTIONS] [FILE|LINK]

  -r  download speed limit (wget format, k-kilobytes, m-megabytes)
  -h  print this help
"
}
#-c  just check links, do not download

# check link format
isLink()
{ 
  link=`echo $1 | sed 's/^http:\/\///; s/^www.//'`
  
  to=`echo $link | grep '^uloz.to/.*/*'`
  cz=`echo $link | grep '^ulozto.cz/.*/*'`
  en=`echo $link | grep '^ulozto.net/.*/*'`
  sk=`echo $link | grep '^ulozto.sk/.*/*'`  
  pl=`echo $link | grep '^zachowajto.pl/.*/*'`
  if [ ! -z "$sk$en$cz$to$pl" ];then
    return 0  
  else
    return 1
  fi
}

while getopts ":hdr:" flag
do
  case $flag in
    'h')  printUsage
          exit;;
    'r')  rate="$OPTARG";;
    #'c')  just_check='true';;
    '?')  error "ivalid option: $OPTARG\n$0 -h for help"
          exit;;
  esac
done

if [ -z ${!OPTIND} ];then
  error "no file or link given\n$0 -h for help"
  exit 2
fi

post_data="captcha%5Bid%5D=$captcha_nb&captcha%5Btext%5D=$captcha_user&freeDownload=St%C3%A1hnout"

get_filename() {
	link=$1
	wget -q -O - "$link" | sed -n '/<a href="#download" class="jsShowDownload">/s/[^>]*>\([^<]*\)<.*/\1/1gp'
}

down() {
	link=$1

file_name=`get_filename $link`

wget --progress=bar:force \
--continue \
--limit-rate="$rate" \
--referer="$link" \
--post-data=$post_data \
-O "$file_name" \
"$link?do=downloadDialog-freeDownloadForm-submit"  2>&1 

}

links=
if [ -f ${!OPTIND} ];then
	links=`cat ${!OPTIND}`
else   
	links=${!OPTIND}
fi

links_valid=0
for link in $links ;do
	isLink $link
	if [ $? -ne 0 ]; then	
		echo invalid link: $link
		links_valid=1
	fi
done

if [ $links_valid -eq 0 ];then
	for link in $links; do
		down $links
	done
else
	exit 1
fi

exit $?

