#!/usr/bin/perl
#
# Find orphaned packages not maintained by the QA group
# without the need of the LDAP gateway to the BTS.
# 
# (c) Emanuele Rocca <ema@debian.org> 
# Distributed under the GNU GPL License (see http://www.gnu.org/gpl)

use LWP::Simple;

use strict;

my $debug = 0;
my $btsurl = "http://bugs.debian.org/wnpp";
my $ptsurl = "http://packages.qa.debian.org";
my $destfile = "/home/ema/public_html/orphaned.html";

my @packageslines = split("\n", get($btsurl))
	or die("\nGetting $btsurl failed");

my $wrong = 0;
my $i;
my $k;
my $j;
my $iorph = 0;
my @merged;
my $imerged = 0;

if (open (HTML, ">$destfile")) {
	print HTML "\n\n<html>\n<title>Orphaned packages not set to QA Group</title>";
	print HTML "\n<body>\n\n";
	close ( HTML );
}
else {
	die ("Unable to open $destfile");
}


foreach (@packageslines) {
  end() if ($packageslines[$i]=~m/<a name=\".*fixed/);
  if ($packageslines[$i]=~/#(.*?): O: (.*?) --/) {
      my $orphaned = $2;
      my $bug = $1;
      print "\nBTS: $orphaned" if $debug;
      print "\nGetting $ptsurl/".$orphaned if $debug;
      my @ptslines = split("\n", get($ptsurl."/".$orphaned))
      	or print ("\nUnable to get the pts page for ".$orphaned);
      $k=0;
      foreach (@ptslines) {
      	if ($ptslines[$k]=~/<a class="email" href="mailto:(.*?)">/) {
		my $email = $1;
		my $name="";
		if ($ptslines[$k]=~/$email\">(.*?)<\/a>/) {
			$name = $1;
		}
		if ($email !~ m/packages\@qa\.debian\.org/i) {
			$packageslines[$i] =~ s/.*?: (.*)<\/a>/$1/g;
			my $subject = $packageslines[$i];
			$packageslines[$i+2] =~ s/.*?">(.*)<\/a>;/$1/g;
			my $submitter = $packageslines[$i+2];
			my $age = "";
			if ($packageslines[$i+3] =~ m/merged.*#(.*?)<\/A>;/) {
				$merged[$imerged] = $1;
				$packageslines[$i+4] =~ s/old/ago/g;
				$age = $packageslines[$i+4];
				$imerged++;
			}
			else {
				$packageslines[$i+3] =~ s/old/ago/g;
				$age = $packageslines[$i+3];
			}
		
			my $not_merged=1;
			for ($j=0;$j<$imerged;$j++) {
				if($bug==$merged[$j]) {
					$not_merged=0;
				}
			}
			if (open (HTML, ">>$destfile") && ($not_merged==1)) {
				print HTML "\n<br><h2>";
				print HTML "<a href=\"http://packages.qa.debian.org/".$orphaned."\">$orphaned</a></h2>";
			       	print HTML "\n<br>Maintainer: $name $email";
				print HTML "\n<br>WNPP bug: <a href=\"http://bugs.debian.org/$bug\">#$bug</a>";
				print HTML "\n<br>Subject: $subject";
				print HTML "\n<br>Submitter: $submitter";
				if ($age>15) {
					print HTML "\n<br><font color=\"red\">Age: $age</font>";
				}
				else {
					print HTML "\n<br>Age: $age";
				}
				$wrong++;
			}
		}
	}
	$k++;
      }
      $iorph++;
  }
  $i++;
}

sub end {
	print HTML "\n\n<br><br><br>";
	print HTML "\nOrphaned packages not set to QA Group: ".($wrong)."<br><br><br>";
	print HTML "\nLast generated on ".`date -R`;
	print HTML "\n</body>\n</html>";
	close (HTML);
	exit();
}
