#!/usr/bin/perl -w
# (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
# Web: http://www.xs4all.nl/~itsme/
#      http://wiki.xda-developers.com/
#
# $Id$
#

use strict;
#
# uses directory listings to generate diskusage information

my $drvlist= shift || "c";
my @drives= split(/\s+/, $drvlist);

my $totals= {};

for my $filename (map { -f $_ ? $_ : "c:/tmp/${_}drive.all" } @drives ) {
    processfile($filename)
}

calculateDirTotals();
printDirTotals();

sub processfile {
    my $filename= shift;

    open FH, "<", $filename or die "$filename: $!\n";

    my $curdir= "";
    while (<FH>) {
        s/\s+$//;;
        if (my ($dirname) = /^ Directory of (.*)$/) {
            $dirname =~ s/\\$//;
            $curdir= $dirname;

            $totals->{$curdir}{bytesize}= 0;
            $totals->{$curdir}{dirsize}= 0;
            $totals->{$curdir}{bytetotal}= 0;
            $totals->{$curdir}{dirtotal}= 0;
        }
        elsif (/^\s+Total Files Listed:/) {
            $curdir= undef;
        }
        elsif (!defined $curdir) {
        }
        elsif (/ <DIR> /) {
        }
        elsif (my ($datetime, $size, $filename)
            = /^(\S+\s+\S+(?:\s\w\w)?)\s+([0-9,]+)\s(\S.*)$/) {
            $size =~ s/,//g;

            $totals->{$curdir}{bytesize} += $size;
        }
        elsif (my ($filecount, $dirsize)= /^\s+(\d+)\sFile\(s\)\s+([0-9,]+)\sbytes$/) {
            $dirsize =~ s/,//g;
            $totals->{$curdir}{dirsize} += $dirsize;
        }
    }
    close FH;
}

sub calculateDirTotals {
    for my $dir (keys %$totals)
    {
        my $path= "";
        for my $pathelem (split(/[\/\\]/, $dir))
        {
            if ($path) { $path .= "\\"; }
            $path.= $pathelem;
            if (! exists $totals->{$path}) {
                $totals->{$path}{bytesize}= 0;
                $totals->{$path}{dirsize}= 0;
                $totals->{$path}{bytetotal}= 0;
                $totals->{$path}{dirtotal}= 0;
            }
            
            $totals->{$path}{bytetotal} += $totals->{$dir}{bytesize};
            $totals->{$path}{dirtotal} += $totals->{$dir}{dirsize};
        }
    }
}

sub printDirTotals {
    for my $dir (sort keys %$totals) {
        printf(" %12.0f %12.0f %s\n", 
            $totals->{$dir}{bytesize} || 0,
            $totals->{$dir}{bytetotal} || 0,
            $dir);
    }
}
