#!/usr/bin/perl -s

# dudf - list the disk usage of the given files with percentages of the drive
# Steve Kinzler, steve@kinzler.com, Dec 15/Feb 16
# https://kinzler.com/me/home.html#unixadm

die "usage: $0 [ -h ] [ file ... ]
	-h	print sizes in a more human readable format\n"
    if $help || ${-help};

%mag = (0 => 'K', 1 => 'M', 2 => 'G', 3 => 'T',
	4 => 'P', 5 => 'E', 6 => 'Z', 7 => 'Y');

@ARGV = ('.') unless @ARGV;

foreach (@ARGV) {
	chomp($du = `du -ksx "$_"`); $du =~ s/\s.*//;
	chomp($df = `df -k   "$_"`); $df =~ s/.*\n//;
	($f, $t, $u) = split(/\s+/, $df);

	# "%s\t%7s\t%4.1f%% of %s used, %4.1f%% of %s tot\n"
	$fmt = ($h) ? "%-25s %7s %5.1f%% of %7s used, %5.1f%% of %7s tot\n"
		    : "%-18s %10s %4.1f%% of %10s used, %4.1f%% of %10s tot\n";
	printf $fmt, "$_:", &h($du), &p($du, $u), &h($u),
				     &p($du, $t), &h($t);
}

sub p { return $_[0] / $_[1] * 100 if $_[1]; 0; }

sub h {	return "$_[0] K" unless $h;
	foreach (sort keys %mag) {
		$s = sprintf('%.0f', $_[0] / 1024 ** $_);
		return "$s $mag{$_}" if length($s) <= 5;
	} }
