#!/usr/bin/perl -w
use strict;
use HTML::TreeBuilder;
use HTML::Element;
use Switch;

sub urlScore
{
	my($url) = @_;
	my $score = 10;
	if ($url =~ /:\d/) { $score -= 20; }
	if ($url =~ /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/) { $score -= 10; }
	if ($url =~ /knightsofreason/) { $score += 5; }
	if ($url =~ /bricosoft/) { $score += 5; }
	if ($url =~ /tremcentral/) { $score += 5; }
	if ($url =~ /randomkeywhacking/) { $score += 5; }
	return ($score);
}

sub validMap
{
	my($map) = @_;
	return (not -e $map and $map =~ m/^map-/ and not $map =~ m/porn/i);
	#return (not -e $map and $map =~ m/^map-/);
}

my $tree = HTML::TreeBuilder->new;
$tree->parse_file("curl -s -S http://betaserv.game-host.org/paklist.html |");
#$tree->parse_file("tmp.html");

my $body = $tree->find('body');

my $curname = undef;

BODYLOOP: foreach my $e ($body->content_list())
{
	if ($e->tag() eq 'h4')
	{
		$curname = $e->as_text();
	}
	elsif ($e->tag() eq 'ul' and $curname and &validMap($curname))
	{
		my $besturl = undef;
		#print "$curname\n";
		foreach my $li ($e->look_down('_tag', 'li'))
		{
			my $url = $li->look_down('_tag', 'a')->attr('href');
			if (&urlScore($url) > ($besturl ? &urlScore($besturl) : 0))
			{
				$besturl = $url;
			}
		}
		if ($besturl)
		{
			print "$curname - $besturl\n";
			system("wget -nv -O$curname '$besturl'");
		}
	}
}

$tree->delete;

