#!/usr/bin/perl

use DBI();
use Socket;
use WWW::Google::PageRank;
use Getopt::Long;
use Config;
use threads;

my $pr = WWW::Google::PageRank->new;
my $dbh = DBI->connect(
	"DBI:mysql:database=seo;host=localhost",
	"seoman",
	"3seA86uD",
	{'RaiseError' => 1}
);

&GetOptions(
	"in=s" => \$inList
);

sub worker {
	my ($user, $pass, $domain, $cur_dbh) = @_;

	if($domain =~ /\b(?:\d{1,3}\.){3}\d{1,3}\b/) {
		$temp = inet_aton($temp);
		$temp = gethostbyaddr($temp, AF_INET);
		
		if($temp ne "") {
			$domain = $temp;
		}
	} 
	
	do_query("INSERT INTO ftp_servers (user, pass, addr, pr) VALUES (?, ?, ?, ?)", undef, $user, $pass, $domain, scalar($pr->get("http://$domain")));
}

sub do_query {
	my $query = @_;

	$dbh->do($query);
}

$Config{useithreads} or die "Recompile Perl with threads to run this program.\n";

open FTPLIST, "<" . $inList;

while() {

	/(.+):(.+)@(.+)/;
	
	my @t = threads->list; my $thr;
	if ($#t < 30) {
		$thr = threads->new(\&worker, $1, $2, $3, $cloned_dbh);
	} else {
		# Loop through all the threads
		foreach (threads->list) {
			# Don't join the main thread
			if ($_->tid && !threads::equal($_, threads->self)) {
				$_->join;
				last;
			}
		}

		$thr = threads->new(\&worker, $1, $2, $3, $cloned_dbh);
	}
}

# Loop through all the threads
foreach (threads->list) {
	# Don't join the main thread
	$_->join if $_->tid
}

close FTPLIST;
$dbh->disconnect();