#!/bin/bash -e
# borken!

timeout=20
proto=http

what=$*
case "$what" in
""|-h|-help|--help)
	prog=$(basename $0)
	echo >&2 usage: "$prog 'name of movie'"
	echo >&2 e.g. : "$prog 'yes men'"
	exit 0
esac

what=$(echo -n "$what" | sed 's,/$,,' | tr -s '_' ' ')
dir=$(echo -n "$what" | tr -sc '[A-Za-z0-9]' '_')
mkdir -p "$dir"
cd "$dir"
if [ ! -s 1.html ]; then
	# wget "https://thepiratebay.se/search/$what/0/7/0" -O 1.html
	wget -T $timeout "$proto://thepiratebay.se/search/$what/0/7/200" -O 1.html
fi

< 1.html perl -ne '
	s/^\s*//g;
	s/[\r\n]//g;
	s/(<\/tr>)/$1\n/;
	$a = s/<\/thead>//; $b = /<\/table>/;
	s/<t[dr].*?>//g;
	s/<\/t[dr]>/\t/g;
	s/\&nbsp;/ /g;
	if ($a .. $b and !$b) {
		print
	}
' | perl -ne '
	chomp;
	@f = split /\t/, $_, -1;
	($seed, $leech) = @f[2,3];
	$_ = $f[1] . "\n";
	warn "$seed $leech     $_\n";
	exit;
	($detail, $title, $magnet) = m{^.*?<a href="(/torrent/.*?)".*?>(.*?)<.*?<a href="(magnet:.*?)"};
	($trust) = m{<img [^>]*alt="(VIP|Trusted)"};
	$trust ||= "";
	$title =~ s/&quot;/"/g;
	$title =~ s/&lt;/</g;
	$title =~ s/&gt;/>/g;
	$title =~ s/&amp;/&/g;
	($date, $size, $user) = m{<font class="detDesc">Uploaded (.*?), Size (.*?), ULed by <.*?>(.*?)<};
	if ($size =~ s/ (\w?)i?B$//) {
		$n = {""=>0, "K"=>1, "M"=>2, "G"=>3, "T"=>4, "P"=>5}->{$1};
		$size = int(1024 ** ($n-2) * $size);
	}
	($m, $d, $y) = $date =~ m{^(\d{2})-(\d{2}) (\d{4})?};
	$y ||= (gmtime())[5] + 1900;
	$date = "$y-$m-$d";
	if ($detail) {
		print join("\t", $magnet, $trust, $seed, $leech, $size, $title, $date, $user, $detail), "\n";
	}
' > 2.tsv

< 2.tsv perl -ne '
	chomp;
	push @rows, [split /\t/, $_, -1];
	END {
		@rows = sort {
			($a_magnet, $a_trust, $a_seed, $a_leech, $a_size, $a_title, $a_date, $a_user, $a_detail) = @$a;
			($b_magnet, $b_trust, $b_seed, $b_leech, $b_size, $b_title, $b_date, $b_user, $b_detail) = @$b;
			($b_s > 0) <=> ($a_s > 0)
			  or ($b_trust eq "VIP") <=> ($a_trust eq "VIP")
			  or ($b_trust ne "") <=> ($a_trust ne "")
#			  or ($b_title =~ /dvdrip/i) <=> ($a_title =~ /dvdrip/i)
			  or ($b_size >= 500) <=> ($a_size >= 500)
			  or ($b_size <= 1000) <=> ($a_size <= 1000)
			  or ($b_size <= 1500) <=> ($a_size <= 1500)
			  or ($b_size <= 2400) <=> ($a_size <= 2400)
			  or $b_seed <=> $a_seed
			  or $a_leech <=> $b_leech;
		} @rows;
		for $row (@rows) {
			print join("\t", @$row), "\n";
		}
	}
' > 3.ordered

< 3.ordered head -n1 | tr '\t' '\n' | 
paste <(for a in magnet trust seed leech size title date user detail; do echo $a; done) - > 4.best

cat 4.best
echo

url=$(<4.best head -n1 | cut -f2)

if [ -z "$url" ]; then
	echo >&2 no movie found
	exit 1
fi

echo "$url" >5.magnet

#file=$(basename $url)
#
#if [ ! -s "$file" ]; then
#	wget -T $timeout "$url" -O "$file"
#	ln -sf "$file" 5.magnet
#fi

echo
sleep 2
#exec rtorrent 5.magnet
exec azureus "$url"
