#!/usr/local/bin/perl -w
use lib "./prec/crontab"; 
require "./prec/ssh2compute.inc.pl";
use DBI;
use prec::crontab::Crontab;


sub init
{
	my $home = $ENV{'HOME'};
	$home = $home.'/prec/ssh2.cron.pl --clean';
	my $cuser = `whoami`;
	my $ct = new Config::Crontab( -owner => '$cuser' );
	my $event = new Config::Crontab::Event( 
					-datetime =>' * 0 * * Fri',
					-hour    => 0,
					-command => $home 
	);
    	$block = new Config::Crontab::Block;
    	$block->last($event);
    	$ct->last($block);
	$ct->write;
}

sub clean
{

my $ctime = `date`;
my $home = $ENV{'HOME'};

my $dbh = DBI->connect("DBI:mysql:$db:$dbserver","$dbuser","$dbpwd");

my $query =  "SELECT dlocation,submitdate,state FROM $jobtable";
my $table_data = $dbh->prepare($query);
$table_data->execute;
# assign fields to variables
my ($submitdate, $state, $dlocation);

$table_data->bind_columns(\$dlocation, \$submitdate, \$state);
my $currdate = `date +%G%j`;
my($lastyear, $lastday) = $currdate =~ m/(\d\d\d\d)(\d\d\d)$/;
$lastday = int($lastday) - $cronlim;
if ($lastday lt 0){
	$lastday = 365 + $lastday;
	$lastyear -= 1;
}
print "Limit: ".$cronlim."  ".$lastday."  ".$lastyear."\n";

# output name list to the browser
while (@results = $table_data->fetchrow()) {
	if ($state == 0){
		
		my ($cyear, $cday) = `date -d '$submitdate' +%G%j` =~ m/(\d\d\d\d)(\d\d\d)$/;
		$cday = int($cday);
		if ($cday lt $lastday){
			#print $cday."  ".$cyear." Current record \n";
			my $out = `rm -rf $home/$dlocation`;
			my $query =  "delete from $jobtable where dlocation=\'$dlocation\'";		
			my $result = $dbh->prepare($query);
			$result->execute;	
		} elsif ($cyear lt $lastyear){
			#print $dlocation."\n";
			my $out = `rm -rf $home/$dlocation`;
                        my $query =  "delete from $jobtable where dlocation=\'$dlocation\'";
                        my $result = $dbh->prepare($query);
		}
	}
}

}


if (not $ARGV[0]) {
	print ("Missing parameters\n");
	exit(0);
} elsif($ARGV[0] eq "--init"){
	init();
	exit(0);
} elsif($ARGV[0] eq '--clean'){
        clean();
	exit(0);
}


