#!/usr/bin/env perl

use strict;
use warnings;

use Getopt::Long;

Getopt::Long::Configure('bundling');

sub usage {
    warn @_, "\n" if @_;

    ( my $cmd_name = $0 ) =~ s,.*/,,;

    die <<EOUSAGE;
Usage: $cmd_name FILE1 [FILE2 ...]
Options:
      --help            Show this help
  -h, --human-readable  Show sizes in kB, MB, GB etc.
  -s, --sparse-only     Only show sparse files
  -n, --nonsparse-only  Only show non-sparse files
  -p, --path            Only show filename path (with -s or -n)
EOUSAGE
}

my %opts = ( verbosity => 1 );
GetOptions( \%opts, 'help', 'human-readable|h', 'sparse-only|s',
    'nonsparse-only|n', 'path|p', )
  or usage();
usage() if @ARGV == 0 or $opts{help};
usage("--sparse-only and --nonsparse-only are mutually exclusive.\n")
  if $opts{'sparse-only'} && $opts{'nonsparse-only'};
usage("--path requires --sparse-only or --nonsparse-only.\n")
  if $opts{path} && !$opts{'sparse-only'} && !$opts{'nonsparse-only'};
usage("--human-readable and --path are mutually exclusive.\n")
  if $opts{'human-readable'} && $opts{'path'};

if ( $opts{'human-readable'} ) {
    eval { require Number::Bytes::Human; };
    usage(
"Need Number::Bytes::Human CPAN module installed for --human-readable.\n"
    ) if $@;
    Number::Bytes::Human->import(qw(format_bytes));
}

if ( !$opts{path} ) {
    if ( $opts{'human-readable'} ) {
        print " size alloc  saved sparse file\n";
    }
    else {
        print "       size       alloc       saved sparse file\n";
    }
}

foreach my $file (@ARGV) {
    check($file);
}

sub check {
    my ($file) = @_;
    my @stat = stat $file or die "stat($file) failed: $!\n";
    my ( $size, $blocks ) = @stat[ 7, 12 ];

    # $size includes unallocated blocks which are nominally "in use"
    # but actually full of zeros so not stored on disk.
    my $allocated  = $blocks * 512;
    my $sparseness = $size ? $allocated / $size : 1;

    # Note sparseness of exactly 1 happens when every byte of the
    # allocated blocks have been used, i.e. with non-sparse files.
    # Therefore non-sparse files will have a value >= 1, and sparse
    # files will have a value < 1.
    my $sparse = $allocated < $size;
    return if $opts{'sparse-only'}    && !$sparse;
    return if $opts{'nonsparse-only'} && $sparse;

    my $saved = $size - $allocated;
    if ( $opts{'human-readable'} ) {
        printf "%5s %5s %6s %6.2f %s\n",
          format_bytes($size),
          format_bytes($allocated),
          format_bytes($saved),
          $sparseness,
          $file;
    }
    elsif ( $opts{path} ) {
        print "$file\n";
    }
    else {
        printf "%11d %11d %11d %6.2f %s\n",
          $size,
          $allocated,
          $saved,
          $sparseness,
          $file;
    }
}
