#!/usr/bin/perl

$quota=50000;   # 50 GB

if($ARGV[0] eq '')
{ 
 print "need directory name to move, usage: check-quota.pl moveto_directory_name\n";
 exit(1);
} 
$length=length($ARGV[0])-1;
if(substr($ARGV[0],$length,1) eq "/") { chop($ARGV[0]); }  # remove tail /
 
print "check quota for current directory\n";
print "if current directory is exceed $quota, then move the oldest ones to $ARGV[0]\n";

CHECK:
system (" du -mL > du.list ");
open(IN,"< du.list");
while(<IN>) 
{ 
 @value=split(/\s+/,$_);
 $size=@value[0];
} 
close(IN);
# print " size= $size \n";

if( $size > $quota )  # if size is bigger than the certain quota, delete the oldest two
{ 
  system ("ls -tr \*.bz2 > dir.list ");
  open(IN,"< dir.list");
  for($i=0;$i<2;$i++) 
  { 
   $a=<IN>; 
   chop($a);
  # system(" rm -R $a");  
  print "mv $a $ARGV[0]\n";
  system("mv $a $ARGV[0]");
  print "ln -s $ARGV[0]/$a .\n";
  system("ln -s $ARGV[0]/$a .");
  # print " rm -R @value[8] ";
  }      
  close(IN);
  goto CHECK;         # check again
}
