#!/usr/bin/perl 

$statusfile = '/var/lib/dpkg/status';
$nonfree = 0;
$partial = 0;
chop($sysname = `uname -n`);

if( -e $statusfile) {
	open(PKG_SOURCE, "< $statusfile") || 
		  die "Cannot open $statusfile - $!\n";
	$/ = "";  #snarf a paragraph at a time
	while(<PKG_SOURCE>) {
		$clump = $_;
		(@pkglines) = split(/\n/, $clump);
		if($#pkglines > 3) {
			$count++;
			$index = 0;
			foreach(@pkglines) {
				chomp;
				$index++;
				if(/^Package:/) {
					($label, $pkg) =  split(/:\s+/,$_,2);
					next;
				}
				if(/^Status:/) {
					($label,  $pkgstatus) = split(/:\s+/,$_,2);
					$pkg_status{$pkg} = $pkgstatus;
					($plan, $state, $status) = split(/\s+/,$pkgstatus);
					next;
				}
				if(/^Section:/) {
					($label, $section) = split(/:\s+/,$_,2);
		         if($section =~ /non-free/) {
						$nonfree = 1;
						$found_descr =0;
						while(! $found_descr) {
							### suggested patch
							if ($index > $#pkglines) {
								$label = '';
								$shortdescr = '';
								last;
							}
						   $dline = $pkglines[$index++];
							if($dline =~ /^Description/) {
						      ($label, $shortdescr) = split(/:\s+/,$dline,2);
								$found_descr = 1;
							}
						}
				      if(lc $status eq 'installed') {
					      $nonfree{$pkg} = $shortdescr;
						}
						else {
							$nonfree_other = 1;
							$other_nonfree{$pkg} = $shortdescr;
						}
					}
				}
			}
		}
	}
	close (PKG_SOURCE);
}
else {
   die "$statusfile does not exist.  Serious problem.\n";
}

#print "$count packages installed\n";

if($nonfree && %nonfree) {
	$~ = "head";
	write ;
	$~ = "nfp";
	foreach $pkgname (sort keys(%nonfree) ) {
		$nfcnt++;
		write ;
	}
}
elsif($nonfree_other && %other_nonfree) {
	$~ = "partialhead";
	write;
	$~ = "pnf";
	foreach $pkgname (sort keys(%other_nonfree)) {
		$pnfcnt++;
		write;
	}
}
else {
	print "No non-free packages installed on $sysname!  rms would be proud. \n"
}


format head =
@||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"Non-free packages installed on $sysname"

.
format partialhead =

@||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
"Non-free packages with status other than installed on $sysname"

.

format nfp =
@<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$pkgname, $nonfree{$pkgname}
.

format pnf =
@<<<<<<<<<<<<<<<<<<<<<<<< @<@<<@< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$pkgname, '(', $pkg_status{$pkgname},')', $other_nonfree{$pkgname}
.
