#!/usr/bin/perl
##
## du(1) clone: Estimate regular file usage, and file, dir and misc count
## Copyright (c) 2008-2010 SATOH Fumiyasu @ OSS Technology, Inc.
##               <http://www.osstech.co.jp/>
##
## License: GNU General Public License version 2 or later
## Date: 2011-01-07, since 2008-03-14
##

use strict;
use warnings;
use File::stat;
use File::Find;

my $w = 16;

my $file_usage_total =
my $file_count_total =
my $dir_count_total =
my $misc_count_total = 0.0;
my $file_count;
my $file_usage;
my $dir_count;
my $misc_count;

@ARGV = qw(.) if (@ARGV == 0);

print sprintf("%${w}s %${w}s %${w}s %${w}s NAME\n",
  'FILE USAGE', 'FILE COUNT', 'DIR COUNT', 'MISC COUNT'
);

my $du = sub {
  if (-f $_) {
    my $stat = stat($_) || die "stat failed: $File::Find::name: $!\n";
    $file_usage += $stat->size;
    $file_count++;
  }
  elsif (-d $_) {
    $dir_count++;
  }
  else {
    $misc_count++;
  }
};

for my $dir (@ARGV) {
  $file_usage = $file_count = $dir_count = $misc_count = 0.0;
  File::Find::find($du, $dir);
  $file_usage_total += $file_usage;
  $file_count_total += $file_count;
  $dir_count_total += $dir_count;
  $misc_count_total += $misc_count;

  print sprintf("%${w}.0f %${w}.0f %${w}.0f %${w}.0f $dir\n",
    $file_usage, $file_count, $dir_count, $misc_count, $dir
  );
}

print sprintf("%${w}.0f %${w}.0f %${w}.0f %${w}.0f TOTAL\n",
  $file_usage_total, $file_count_total, $dir_count_total, $misc_count_total
);

