#!/usr/bin/perl -w

use strict;

use Astro::Time;
use Getopt::Long;

system("renice 19 $$\n");

my $path;
my $age = '2h';
my $delay = 2;
my $help = 0;

GetOptions('age=s'=>\$age, 'help'=>\$help, 'delay=i'=>\$delay);

if ($help) {
  print<<EOF;

  diskclean.pl -age <age> [-delay <delay>] [-help] 

  Slowly deletes LBADR data files older than "age" 

 Options:
    -age     Delete files older than age (e.g. 100s, 60m, 10h)
             Defaults to 2hours
    -delay   Sleep for delay seconds between deletes. Default 2seconds
    -help    This mesage

EOF
  exit(1);
}

if (@ARGV==0) {
  $path = '.';
} elsif (@ARGV==1) {
  $path = shift;
} else {
  die "Usage: diskclean.pl [options] [<path>]\n";
}

if ($age =~ /^([+]?\d*(?:\.\d*)?)\s*([hmsHMS])?$/) {
  die "Missing value for -age!\n" if (! defined $1 || $1 eq '');

  $age = $1;

  my $type = 'h';
  $type = lc($2) if (defined $2 && $2 ne '');

  print "\n";
  if ($type eq 'h') {
    printf "Will delete files older than %.1f hours\n", $age;
    $age /= 24; 
  } elsif ($type eq 'm') {
    printf "Will delete files older than %.0f minutes\n", $age;
    $age /= 24*60; 
  } elsif ($type eq 's') {
    printf "Will delete files older than %.0f seconds\n", $age;
    $age /= 24*60*60; 
  }
} else {
  die "Did not understand -age $age\n";
}

my %files;

while (1) {
  print "\n Updating file listing\n";

  opendir(DIR, $path) || die "Could not list contents of data dir $path\n";
  while (my $datafile = readdir(DIR)) {
    next if $datafile eq '..';
    next if $datafile eq '.';
    next if (! -f "$path/$datafile");
    if ($datafile =~ /^.+\.lba$/) {

      # Could add code to check hash if we change the way we update the list
      # ie now the hash is empty each time but this may change

      # Get the time code
      open(DATA, "$path/$datafile") 
	|| die "Could not open $datafile  for reading: $!\n";
      my $time = <DATA>;
      chomp $time;
      close(DATA) || die "Error with file $datafile: $!\n";

      if ($time =~ /^TIME (\d\d\d\d)(\d\d)(\d\d):(\d\d)(\d\d)(\d\d)$/) {
	my $year = $1;
	my $month = $2;
	my $day = $3;
	my $hour = $4;
	my $min = $5;
	my $sec = $6;
        
	my $mjd = cal2mjd($day, $month, $year,
			  (($sec/60+$min)/60 + $hour)/24);

	$files{$datafile} = $mjd;
      } else {
	warn "Unexpected time string $time in $datafile\n";
      }
    } else {
      print "Ignoring $datafile\n";
    }
  }
  closedir(DIR);

  if (scalar(%files)) {
    while (scalar(%files)) {
      my $mjd = now2mjd()-$age;

      while (my ($file, $filemjd) = each %files) {
	if ($filemjd<$mjd) { # Want to delete this old file
	  my $cnt = unlink "$path/$file";
	  if ($cnt==1) {
	    print "Deleted $file\n";
	    sleep($delay);
	  } else {
	    warn "Failed to unlink $file!!!\n";
	  }
	  delete $files{$file}; # If we don't remove it from the hash we will never finish
	                        # the loop
        }
      }
      sleep(10);
    }
  } else {
    warn "No files to delete. Waiting\n";
    sleep(600);
  } 
}
