#!/usr/bin/perl -T
#$Id: cleanup_old_data.pl,v 1.3 2024/05/23 10:42:25 sqko Exp $
use strict;
use warnings;
use RFC::Main;
use RFC::Header;
use RFC::Rig;
use SemaforeFile;
use File::Path;
my $r = shift;
if ($r && $r =~ /(\d+)/)
{
    $r = $1;
}
else
{
    exit;
}
my $rig = RFC::Rig->new($r,0,'nocheck');
$rig->check_run;
my $debug = 0;
my $interval = 5; # 5 years

foreach (@ARGV)
{
    $debug = 1 if (/--debug/);
    if (/--interval\=([\d\.]+)/)
    {
        $interval = $1;
    }
}
$interval = 2 if ($interval < 2);

my $maxtest = $rig->session();
my $cutoff = time - $interval * 60 * 60 * 24 * 265;
for (my $test = 0; $test < $maxtest; $test++)
{
    print "Testing $rig test $test\n" if ($debug);
    my $dir = $rig->webdir($test);
    my $f = $dir.'jdata';
    next unless (-e $f);
    my $fid = SemaforeFile->new($f);
    $fid->open_readback();
    my $lastline = $fid->readline();
    $fid->close();
    if ($lastline && $lastline =~ /utime\s+(\d+)/)
    {
	next if ($1 > $cutoff);
    }
    else
    {
	next;
    }
    print "Prepareing for delete of data\n" if ($debug);
    if (-e $dir.'raadata')
    {
	print "Removing daily raadata files\n" if ($debug);
	opendir DIR,$dir or die "Could not open directory $dir for writing";
	my @raadata = grep { /raadata\.\d/ } readdir(DIR);
	closedir DIR;
	foreach my $file (@raadata)
	{
	    if ($file =~ /^([\w\.\-\:]+)$/)
	    {
		$file = $1;
	    }
	    else
	    {
		next;
	    }
	    my $ff = $dir.$file;
	    print "Deleting $ff\n" if ($debug);
	    unlink($ff) or die "Could not remove file $ff $!\n";
	}
	print "Removing daily plots\n" if ($debug);
	opendir DIR,$dir or die "Could not open directory $dir for writing";
	my @daily = grep { /^\d+\:\d+\:\d+$/ } readdir(DIR);
	closedir DIR;
	foreach my $d (@daily)
	{
	    if ($d =~ /^([\d\:]+)$/)
	    {
		$d = $1;
	    }
	    else
	    {
		next;
	    }
	    my $dd = $dir.$d;
	    print "Removing $dd\n" if ($debug);
	    rmtree($dd) or die "Could not remove directory $dd $!\n"
	}
    }
}
