All pastes #929356 Raw Edit

Miscellany

public text v1 · immutable
·published 2008-03-05 18:35 UTC
rendered paste body
#!/usr/bin/perl -w

use strict;
use File::Find;
use File::stat;
use Getopt::Std;

my %opts;
getopts('hd:p:s:t:rm',\%opts);

usage() if ( $opts{h} || ( !$opts{d} ) );
my ($directory) = ("")x1;

if ($opts{d}) { $directory = $opts{'d'}; }
if ($opts{r}) { report(); }
if ($opts{m}) { manage(); }

my @dirList = "";

sub usage
{
  print "Usage:\n\n";
  print "\t dirmonitor -d <dir>";
}


sub report
{

  my ($owner,@ownersDirs,@ownersDirSizes,@fileList,%HoA_Sizes,%HoA_Dirs,@tokens,$user,$file,$dir,$size,$cat,$sum,%dirHash) = ("")x14;
  print "Inspecting directory: $directory ...\n\n";

  #find( {wanted => \&wanted, dangling_symlinks => 1 }, $directory);
  find(\&wanted, $directory);

  #print "values: @dirList\n";
  # Create a hash of arrays with our newly found directories, each array in the
  # hash contains directories that the user owns.  Each array is keyed by the
  # owners user name.
  foreach (@dirList) {
    $dir = $_;
    $user = getpwuid(stat($dir)->uid);
    # split up the info that du returns into tokens, resuse @tokens array
    #@tokens = split(' ', qx(du -S "$dir"), 2);
    #$size = $tokens[0];
    $size = -s $dir;
    # push the sizes of the users directories onto users stack
    push @{$HoA_Sizes{$user}}, $size;
    push @{$HoA_Dirs{$user}}, $dir;

  }

  # sum up the sizes of directories that the user owns
  foreach $owner ( keys %HoA_Sizes ) {
    # dereference the array reference and grab the list of values
    @ownersDirSizes = @{ $HoA_Sizes{$owner} };
    @ownersDirs = @{ $HoA_Dirs{$owner} };

    @dirHash{ @ownersDirs } = @ownersDirSizes;

    #for my $i (0 .. $#ownersDirs) {
    #  if ($i ne $directory) {
    #    $sum += $ownersDirSizes[$i];
    #    $dirHash{$ownersDirs[$i]} = $ownersDirSizes[$i];
    #    print "$ownersDirSizes[$i]  dir: $ownersDirs[$i]\n";
    #  }
    #}

    foreach my $toke ( keys %dirHash ) {
      $sum += $dirHash{$toke};
      #print "$dirHash{$toke}KB\t $toke\n";
    }

    push @{$HoA_Sizes{$owner}}, $sum;
    #print "sum is: $sum\n";
    $sum = 0;
  }

  # sort the hash of arrays by comparing the first value of a users
  # array(sum of all users dirs)
  foreach $owner ( sort { $HoA_Sizes{$b}->[-1] <=> $HoA_Sizes{$a}->[-1] } keys %HoA_Sizes ) {
   # print "$owner: @{[int($HoA_Sizes{$owner}->[-1]/1000000)]}MB\n";
    #print "$owner: @{[$HoA_Sizes{$owner}->[-1]/1000000]}MB\n";
    print "$owner: ";
    printf "%2.2f", @{[$HoA_Sizes{$owner}->[-1]/1000000]};
    print "MB\n";
  }

}

sub wanted {
  #if (-d $_) {
    if ($_ ne ".") {
      #print "we have: $_ and $directory\n";
      push(@dirList,$File::Find::name);
    }
  #}

}