#!/usr/local/bin/perl
# rpmfind.cgi
# Display a search window for rpmfind.net

require './software-lib.pl';
&ReadParse();

&header();
print <<EOF;
<script>
function sel(m)
{
window.opener.ifield.value = m;
window.close();
return false;
}
</script>
EOF

print "<form action=rpmfind.cgi>\n";
print "<input type=submit value='$text{'rpm_search'}'>\n";
print "<input name=search size=20 value='$in{'search'}'><br>\n";
print "</form><hr>\n";

if ($in{'search'}) {
	# Show the results from the rpmfind command
	local @rv;
	open(SEARCH, "rpmfind --apropos '$in{'search'}' 2>/dev/null |");
	while(<SEARCH>) {
		if (/^(\d+):\s+((ftp:|http:|https:)\S+)/) {
			local $pkg = { 'url' => $2 };
			$pkg->{'source'}++ if ($pkg->{'url'} =~ /\.src\.rpm$/ ||
					       $pkg->{'url'} =~ /\.srpm$/);
			if ($pkg->{'url'} =~ /\/(([^\/]+)-([^\-\/]+)-([^-\/]+).([^-\/]+)\.rpm)$/) {
				$pkg->{'file'} = $1;
				$pkg->{'prefix'} = $2;
				$pkg->{'version'} = $3;
				$pkg->{'release'} = $4;
				$pkg->{'arch'} = $5;
				if ($pkg->{'version'} =~ /^(\d+)\.([0-9\.]+)$/){
					local ($v1 = $1, $v2 = $2);
					$v2 =~ s/\.//g;
					$pkg->{'version'} = "$v1.$v2";
					}
				}
			elsif ($pkg->{'file'} =~ /\/([^\/]+)$/) {
				$pkg->{'file'} = $1;
				}
			if ($pkg->{'url'} =~ /redhat\/[^\/]+\/([^\/]+)/) {
				$pkg->{'dist'} = "Redhat $1";
				}
			elsif ($pkg->{'url'} =~ /pld.org.pl\/([^\/]+)/) {
				$pkg->{'dist'} = "PLD $1";
				}
			elsif ($pkg->{'url'} =~ /mandrake\/([^\/]+)/) {
				$pkg->{'dist'} = "Mandrake $1";
				}
			elsif ($pkg->{'url'} =~ /mandrake-devel/) {
				$pkg->{'dist'} = "Mandrake Cooker";
				}
			elsif ($pkg->{'url'} =~ /yellowdog(\/old_releases)?\/([^\/]+)/) {
				$pkg->{'dist'} = "YellowDog $2";
				}
			elsif ($pkg->{'url'} =~ /turbolinux/) {
				$pkg->{'dist'} = "TurboLinux";
				}
			$_ = <SEARCH>;
			if (/^\s+(\S+)\s*:\s*(.*)/) {
				$pkg->{'name'} = $1;
				$pkg->{'desc'} = $2;
				push(@rv, $pkg);
				}
			}
		}
	close(SEARCH);

	@rv = grep { !$_->{'source'} } @rv;
	@rv = sort { local $vc = $b->{'version'} <=> $a->{'version'};
		     local $rc = $b->{'version'} <=> $a->{'version'};
		     return $vc ? $vc : $rc } @rv;
	if (@rv) {
		print "<table width=100%>\n";
		foreach $r (@rv) {
			print "<tr>\n";
			print "<td><a href='' onClick='sel(\"$r->{'url'}\")'>",
			      "$r->{'file'}</a></td>\n";
			print "<td>$r->{'dist'}</td>\n";
			print "<td>$r->{'desc'}</td>\n";
			print "</tr>\n";
			}
		print "</table>\n";
		}
	else {
		print "<b>$text{'rpm_none'}</b> <p>\n";
		}
	}

&footer();

