#!/usr/bin/perl

use strict;
use warnings;

use Unix::Getrusage;

if (!defined($ENV{'GSDLHOME'}))
{
  print STDERR "Error! GSDLHOME not in environment (have you sourced setup.bash?)\n";
  exit(0);
}

if (!defined($ARGV[0]))
{
  print STDERR "Usage: rm_archives.pl <collection name> [<debug>]\n";
  exit(0);
}

# Clean up command...
my $cmd = 'rm -rf ';
my $del_count = 0;

# Check the archives directory as a priority
my $archives_dir = $ENV{'GSDLHOME'} . '/collect/' . $ARGV[0] . '/archives';
if (-d $archives_dir)
{
  $cmd .= ' "' . $archives_dir . '"';
  $del_count++;
}

# Cache dir too for video or other caching plugins
my $cached_dir = $ENV{'GSDLHOME'} . '/collect/' . $ARGV[0] . '/cached';
if (-d $cached_dir)
{
  $cmd .= ' "' . $cached_dir . '"';
  $del_count++;
}

# There may also be a logs directory we'll nuke, for clarity sake
my $logs_dir = $ENV{'GSDLHOME'} . '/collect/' . $ARGV[0] . '/logs';
if (-d $logs_dir)
{
  $cmd .= ' "' . $logs_dir . '"';
  $del_count++;
}

# Now run the built up command (assuming we found something to delete)
if ($del_count > 0)
{
  if (defined ($ARGV[1]))
  {
    print "CMD: " . $cmd . "\n";
  }
  `$cmd`;
}
else
{
  print "Warning - no previous archives found: " . $archives_dir . "\n";
}

# Write out timing statistics
if (defined ($ARGV[1]))
{
  my $rusage_struct = getrusage();
  my $rusage_children_struct = getrusage_children();
  print "\n";
  print "*************************************************\n";
  print "DEBUG: Script Timing/Usage for rm_archives.pl\n";
  print "*************************************************\n";
  my $rusage_fields = {'user time used'=>'ru_utime',
                       'system time used'=>'ru_stime',
                       'maximum resident set size'=>'ru_maxrss',
                       'integral shared memory size'=>'ru_ixrss',
                       'integral unshared data size'=>'ru_idrss',
                       'integral unshared stack size'=>'ru_isrss',
                       'page reclaims'=>'ru_minflt',
                       'page faults'=>'ru_majflt',
                       'swaps'=>'ru_nswap',
                       'block input operations'=>'ru_inblock',
                       'block output operations'=>'ru_oublock',
                       'messages sent'=>'ru_msgsnd',
                       'messages received'=>'ru_msgrcv',
                       'signals received'=>'ru_nsignals',
                       'voluntary context switches'=>'ru_nvcsw',
                       'involuntary context switches'=>'ru_nivcsw'};
  foreach my $rusage_title (sort keys %{$rusage_fields})
  {
    my $rusage_field = $rusage_fields->{$rusage_title};
    my $total = $rusage_struct->{$rusage_field} + $rusage_children_struct->{$rusage_field};
    print ' * ' . sprintf("%-30s", ucfirst($rusage_title) . ': ') . $total . "\n";
  }
  print "*************************************************\n";
  print "\n";
}

exit(0);
