#!/usr/bin/perl -w

use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $query = new CGI;

print "Content-type: text/html\n\n";
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">', "\n";
print "<html><head><title>bpo package search</title></head><body>\n";


sub sendtheform {
    print "<form action=\"search.pl\" method=\"POST\">\n";
    print "<H1>bpo package search</H1>\n";
    print "<input type=\"text\" name=\"query\" size=\"40\" maxlength=\"40\">\n";
    print "<td valign=\"top\"><input type=\"submit\" name=\"send\" value=\"send\"></td>\n";
    print "</form>\n";
}

sub performsearch {
    my $query = @_[0];
    print "<p>Server performed a query with the keyword ";
    print $query;
    print "</p>\n";

    foreach my $value (qw/ main contrib non-free /) {
	print "<h1>Results for packages listed in ", $value, ":</h1>\n";

	open SOURCES, "$value/Sources" or die "Can't open Source file: $!";
	my @sourceslist=<SOURCES>;
	close SOURCES;
	
	for (my $i = 0; $i < @sourceslist; $i++) {
	    $_ = @sourceslist[$i];
	    if (/^Package:.*$query.*/) {
		my $pver=&findnextver($i, @sourceslist);
		my $pdir=&findnextdir($i, @sourceslist);
		print "<p>\n";
		print @sourceslist[$i],"<br>\n";
		print $pver, "<br>\n";
                print "<a href=\"http://www.backports.org/debian/", $pdir,"\">http://www.backports.org/debian/",$pdir,"</a><br>\n";
		print "</p>\n";

	    }
	}

    }
}


sub findnextver {
    my ($startpos, @list) = @_;
    for (my $i = $startpos; $i < @list; $i++) {
	$_ = @list[$i];
	if (/^Version:.*/) {
	    return $_;
	    last;
	}
    }
}

sub findnextdir {
    my ($startpos, @list) = @_;
    for (my $i = $startpos; $i < @list; $i++) {
	$_ = @list[$i];
	if (/^Directory:.*/) {
	    my @dirsplit = split / /, $_;
	    chomp(@dirsplit[1]);
	    return @dirsplit[1];
	    last;
	}
    }
}



 if ($query->param('send') eq "send") {
    &performsearch($query->param('query'));
} else {
    &sendtheform();
}


print "</body></html>\n";
