package Service;
use Util;
use strict;
use Debug;

# clean  subdirectories

sub clean_core {
  my($class, $max) = @_;

  my $renv = System->get_renv();
  return if ($renv->{solution} ne "se2");

  my $dir  = $renv->{"corefiles.base"} || "/var/crash";
  opendir(O, $dir);
  my @D = readdir(O);
  closedir(O);

  foreach my $d (@D) {
     next if (substr($d,0,1) eq ".");
     if (-d "$dir/$d") {
         $class->clean_dir("$dir/$d", $max);
     }
     if($d =~ /dsp/){
        # Must clean triage files
	# Each run could have 5 processors * 6 boards or 30 files.
	# Want to keep around 2 runs worth.
	$class->clean_triage("$dir/$d", 60);
     }

  }
}

sub clean_dir {
  my($class, $dir, $max) = @_;
  my(@A);

  opendir(O, $dir);
  my @F = readdir(O);
  closedir(O);

  foreach my $f (@F) {
     next if (substr($f,0,1) eq ".");
     next if($f =~ /triage/);

     my $age = Util->get_file_created("$dir/$f");
     push(@A, "$age\t$f");
  }

  @A = sort(@A);

  my($x);
  for ($x=0; $x <= $#A - $max; $x++) {
     my($time, $f) = split(/\t/,$A[$x]);
     unlink "$dir/$f";
  }
}
sub clean_triage {
  my($class, $dir, $max) = @_;
  my(@A);

  opendir(O, $dir);
  my @F = readdir(O);
  closedir(O);

  foreach my $f (@F) {
     next if (substr($f,0,1) eq ".");
     next if($f !~ /triage/);

     my $age = Util->get_file_created("$dir/$f");
     push(@A, "$age\t$f");
  }

  @A = sort(@A);

  my($x);
  for ($x=0; $x <= $#A - $max; $x++) {
     my($time, $f) = split(/\t/,$A[$x]);
     unlink "$dir/$f";
  }
}
1;
