#!/usr/bin/perl

if ($#ARGV < 1) {
 printf "Usage trim <path> <days> [exlude day]\n";
 exit 1;
} else {
  $path = @ARGV[0]; 
  $tdays = @ARGV[1]; 
  if ($#ARGV == 2) {
    $ex = @ARGV[2]
  } else {
    $ex = 0;
  }
}

open (hd,">rm_old_files.sh");
if (hd < 0) {
  print "Couldn't create rm_old_files.sh\n";
  exit 1;
}

opendir(Dir, $path) || { exit 1 };
while ($file = readdir(Dir))
{  
  @temp=split (/-/,$file);
  if ($#temp eq 2) {
    $d = @temp[0];
    $m = @temp[1] - 1;
    $y = @temp[2];
    if ($ex eq ($d + 0)) {
      next;
    }
    if ($y < 100) {
      $y += 2000;
    }
    $diff = getdate($d, $m, $y);
#    print "$d, $m, $y - $diff\n";
#    $tmp = int(time / 86400);
#    print " $tmp\n";
    if ($diff > -1) {
      $diff = int(time / 86400) - $diff;
      if ($diff > $tdays) {
        print hd "rm $path/$file -R\n";
      }
    }
  }
}

closedir(Dir);
chmod(0770, "./rm_old_files.sh");
exit 0;

sub getdate() {
  @months = (31,29,31,30,31,30,31,31,30,31,30,31);
  if ((@_[1] > $#months) or (@_[1] < 0) or (@_[2] < 0) or (@_[0] < 0) or (@_[2] < 1970)) {
    return -1;
  }
  if (@_[0] > @months[@_[1]]) {
    return -1;
  } 
  $days = 0;
  for $i(0..@_[1]-1) {
    $days += @months[$i];
    if ($i eq 1) {
      if (@_[2] % 4 ne 0) {
        $days -= 1;
      }
    }
  }
  $add=int((@_[2] - 1972) / 4);
#  $days += (@_[2] - 1970) * 365 + int((@_[2] - 1 - 1972) / 4) + @_[0];
  $days += (@_[2] - 1970) * 365 + int((@_[2] - 1) / 4) - int(1972 / 4) + @_[0];
  return $days;
}
