#!/usr/bin/perl -w
# Version: 20011114.1
# Copyright (c) 2001 Kamil Kisiel <kamil@kamilkisiel.net>
# Feta plugin for determining the size of installed packages.
# Licensed under the GNU GPL v2

use strict;

use Getopt::Std;

#
# Some (hopefully) self-explanatory variables. 
#
my %packages; 
my $currentpackage;
my $totalsize;
my $package;
my $packagecount;

#
# Allow for -s and -r command line switches.
#

my %opts;
getopts('qVtysr', \%opts);

#
# Read the dpkg database and create a hash of all installed packages and their sizes.
#
open(DPKG, '/var/lib/dpkg/status');
while ( <DPKG> ){
	if (/^Package\: (.+)\n/){
		$currentpackage = $1;
	}
	#
	# Add packages that are not installed to the "null" key of the hash, this is removed below.
	# 
	if (/^Status\: (.+)\n/){
		unless ($1 eq "install ok installed" || $1 eq "hold ok installed"){
			$currentpackage = 'null';
		}
	}
	if (/^Installed-Size\: (.+)\n/){
		$packages{$currentpackage} = $1;
	}		
}
close(DPKG);
delete $packages{'null'};

#
# Set the page size to the size of the hash plus 4 lines, to accomodate header.
#
$= = (scalar keys %packages) + 4 ;

#
# Print out the list of packages in an order depending on the command line options.
# 
# s - by size
# r - reversed
# 
if ( $opts{'s'} && $opts{'r'} ) {
 	foreach $package (reverse sort { $packages{$a} <=> $packages{$b} } keys %packages){
		output($package);
	}

} elsif ( $opts{'s'} ) {
	foreach $package (sort { $packages{$a} <=> $packages{$b} } keys %packages){
		output($package);
	}

} elsif ( $opts{'r'} ) {
	foreach $package (reverse sort keys %packages){
		output($package);
	}

} else {
	foreach $package (sort keys %packages){
		output($package);
	}
}

#
# Print the total size of all packages at the bottom
#
if (!$opts{'q'}) {
 print "\nTotal size: $totalsize kB\n";
 print "Packages counted: $packagecount\n";
}

sub output {
	my $package = shift;
	write;
	$totalsize += $packages{$package};
	$packagecount++;
}

format STDOUT_TOP =
Package Name							Size
================================================================================
.

format STDOUT =
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<       @>>>>>>>> kB
$package,						$packages{$package}
.
