#! /usr/bin/env perl
use Getopt::Long;
use CondorUtils;
use Cwd;
use Soar;

Soar::DebugOff();

$jobout = "./doextract.out";
$savefile = "./ENVVARS";

# Dagman passes node which maps to both where the job is running
$mode = $ARGV[0];
$cwd = getcwd();

print "Starting postjob here and removing tar ball of input data<$cwd>\n";

Soar::DebugOff();
Soar::ReadSetEnv($savefile);

$topdir = $ENV{TOPDIR};
$runloc = $ENV{RUNLOC};
$resultsloc = $ENV{RESLOC};
$tarcache = $ENV{TARCACHE};
$datasets = $ENV{DATASETS};

print "Top = $topdir\n";
print "DATA = $datasets\n";
print "RESULTS = $resultsloc\n";
print "RUNDIR = $runloc\n";
print "TARCACHE = $tarcache\n";
print "CWD = $cwd\n";

$runs = Soar::FindImageRuns($cwd);
@runlist = split ":", $runs;

if($mode =~ /.*A.*/) {
	print "Removing All\n";
	$mode = "CRLA";
}

foreach my $set (@runlist) {
	my $res = "$resultsloc/$set/*";
	my $cache = "$tarcache/$set" . ".tar.gz";
	print "removing $res and $cache for $set\n";
	if($mode =~ /.*D.*/) {
		print "Removing Datasets\n";
		runcmd("rm -rf $datasets/$set",{emit_output=>0});
	}
	if($mode =~ /.*C.*/) {
		print "Removing TAR cache\n";
		runcmd("rm -rf $cache",{emit_output=>0});
	}
	if($mode =~ /.*R.*/) {
		print "Removing Results\n";
		runcmd("rm -rf $res $resultsloc/*.zip $resultsloc.tar.gz",{emit_output=>0});
	}
	if($mode =~ /.*L.*/) {
		print "Removing Logs\n";
		opendir RUNS, "\." or die "can not open run<$runloc>:$!\n";
		foreach my $name (readdir RUNS)
		{
			next if $name =~ /^\.\.?$/;
			next if -f $name;
			if(-d $name) {
				chdir("$name");
				system("pwd");
				print "entering job $name and cleaning\n";
				runcmd("rm -f *.log *.err *.out ",{emit_output=>0});
				chdir("..");
				system("pwd");
				print "Back from job $name\n";
			}
		}
	}
}
#print "Tarcache now holds:\n";
#runcmd("ls $tarcache",{emit_output=>0});
#print "Results now holds:\n";
#runcmd("ls $resultsloc",{emit_output=>0});
print "Leave basic run result data like report, logs and profile\n";
print "Run dir now holds:\n";
runcmd("ls -Rl",{emit_output=>0});
print "Datasets now holds:\n";
runcmd("ls $datasets",{emit_output=>0});

exit(0);

# =================================
# print help
# =================================

sub help
{
    print "Usage: clean.pl mode
			Modes: all  = (data, tarcache, resulults, rundata)
			       large = (tarcache, resulults, rundata)
        Options:
            [-h/--help]                             See this
			\n";
}
