#!/usr/bin/perl

# $Id: duports.pl,v 1.1 2004/09/05 19:04:06 ecu Exp ecu $
# duports.pl - how many space does your FreeBSD ports take ?
# Nicolas Jombart <ecu@ipv42.net>
# ex:ts=4

use strict;

my $pkg_dir="/var/db/pkg/";
my $PREFIX="/usr/local";       # default if not @cwd ...

my $unit = '';
my $total = 0;

my @ports = grep { /CONTENTS$/} `find $pkg_dir`;
chomp @ports;

foreach my $port (@ports) {
my $size = 0;
	open(FH, "<", $port) || die "Can't open $port\n";
	while(my $f=<FH>) {
		chomp $f;
		if ($f =~ /^\@cwd (.*)$/ && $1 !~ /\./) { $PREFIX = $1; }
		next if $f =~ /^(\@|\+)/;
		#print "file : $PREFIX/$f  ";
		$size += (stat("$PREFIX/$f"))[7];
		#print "size : $size\n";
	}
	$port =~ /\/var\/db\/pkg\/(.+)\/\+CONTENTS/;
	my $name = $1;
	$total += $size; 
	if($size > 1024) { $unit = 'K'; $size = $size / 1024; }
	if($size > 1024) { $unit = 'M'; $size = $size / 1024; }
	if($size > 1024) { $unit = 'G'; $size = $size / 1024; }
	printf "%10d%s %s\n", $size, $unit, $name;
	$unit = '';
}

if($total > 1024) { $unit = 'K'; $total = $total / 1024; }
if($total > 1024) { $unit = 'M'; $total = $total / 1024; }
if($total > 1024) { $unit = 'G'; $total = $total / 1024; }

printf "\n%10d%s total\n", $total, $unit;
