#!/usr/bin/perl -w
use strict;
$|=1;
use HTTP::Request::Common qw(POST GET);
use LWP::Simple;
use LWP::UserAgent;

my $ua= LWP::UserAgent->new();
$ua->agent("Mozilla/4.75 [en] (X11; U; Linux 2.2.17 i686)");

my $querylist= @ARGV?\@ARGV:MakeIdaProQueryList();
for my $query (@$querylist) {
    my $googlehtml= QueryGoogle($query);
    my $result= ParseGoogle($googlehtml);

    PrintResult($result);
}

exit(0);

sub MakeIdaProQueryList {

    my $parts= [
        [qw(ida)],
        ["", "."],
        ["", "pro"],
        ["", "-"],
        ["4"],
        ["", "."],
        [10..65],
        ["", "a"],
        ["."],
        [qw(exe zip arj rar lha tgz tar.gz)],
    ];

    my $total_choices= getTotalChoices($parts);

    my @querylist;
    for my $i (0..$total_choices-1) {
        push @querylist, GetQuery($parts, $i);
    }

    return uniq(\@querylist);
}
sub uniq {
    my ($list)= @_;
    my %ref;
    $ref{$_}++ for (@$list);
    return [keys %ref];
}

sub QueryGoogle {
    my $query= shift;
    my $pagerq= GET "http://www.google.com/search?q=\"$query\"&num=100";
    my $rp= $ua->request($pagerq);

    return $rp->content;
}
sub GetQuery {
    my ($parts, $qid)= @_;

    my $query="";

    for my $part (@$parts) {
        my $n_choices= scalar @$part;
        my $choice= $qid%$n_choices;
        $qid= int($qid/$n_choices);
        $query .= $part->[$choice];
    }
    return $query;
}

sub getTotalChoices {
    my ($parts)= @_;
    my $total= 1;
    for my $part (@$parts) {
        my $n_choices= scalar @$part;
        $total *= $n_choices;
    }
    return $total;
}

sub ParseGoogle {
    my ($html)= @_;

    my @result;
    my @parts= split(/<p>/, $html);
    for my $part (@parts) {
        next if ($part !~ /href/);
        next if ($part =~ /Did you mean(?: to search for)?:.*\/search/);
        next if ($part =~ /Category:.*href=.*directory.google.com/);
        next if ($part =~ /Result.*?Search took.*?second/i);
        return [] if ($part =~ /<br>Your search - <b>.*?<\/b> - did not match any documents/i);
        my $url;
        if (($url)= ($part =~ /<a href=["']?(.*?)["']?>/i)) {
#                  && $url && ($url !~ /google\.com/) ) {

            if ($url !~ /google\.com/ && $url =~ /^\w/) {
                push @result, $url;
            }
        }
    }
    return \@result;
}
sub PrintResult {
    my ($results) = @_;
    for my $url (@$results) {
        print "$url\n";
    }
}
