#!/dataserfs/libs-2024-01-11/bin/perl -w

use strict;

	# ddu-table-maintenance
	# table_maintenance
	# SPD + SVC
	# driven by crontab
	#

delete @ENV{'PATH','IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
$ENV{'PATH'} = '/bin:/usr/bin';

use DBI;
use File::FcntlLock;
use Carp::Assert;


my $db  	= "ddu";
my $db_host  	= "localhost";
my $db_user  	= "ddu";
my $db_pw  	= "ddu";

my $lockfile	= "/var/run/ddu-table-maintenance.lock";
my $logfile	= "/var/log/ddu-table-maintenance.log";

my @MysqlOptions = qw(  DBI:MariaDB:
                        mariadb_server_prepare=0
                        mariadb_read_default_file=/etc/my.cnf );




# #####################################################################
sub CloseDB{ my( $dbh ) = @_;
# #####################################################################
	assert($dbh);
        $dbh->disconnect();
} # CloseDB



# #####################################################################
# $port is optional
sub OpenDB{my($host,$database,$db_user,$db_pass, $port) = @_;
# #####################################################################
	assert($host);
	assert($database);
	assert($db_user);
	assert($db_pass);
	# port may be NULL

my $dsn = join(';', @MysqlOptions, "host=$host", "database=$database");
        if ( defined $port ) {
                $dsn .= ";port=$port";          # add port if defined
        } # if

        my $dbh = DBI->connect($dsn, $db_user, $db_pass);

 return($dbh);
} # OpenDB
# #####################################################################



# #####################################################################
sub logmsg{my($msg) = @_;
# #####################################################################
	print STDERR  scalar localtime(), " ", $msg, "\n";
} # logmsg


















# #####################################################################
sub main_thing{my($max_hot_days) =@_;
# #####################################################################

	$max_hot_days = 3 if( !$max_hot_days);


	#open(STDOUT,">>$logfile") || die( "logfile $!");
	#open(STDERR,">>$logfile") || die( "logfile $!");

	# lock to make sure we run only once
	# open for append ( i.e. create if needed )
	open(LOCK, ">>$lockfile" ) || die( "lockfile $!");
	my $fs = new File::FcntlLock( l_type => F_WRLCK);
	if ( ! defined $fs->lock(\*LOCK, F_SETLK) ) {
		#unable to lock
		exit (0) if ( $fs->error =~ /already locked/ );
		die("unable to lock: $!, " . $fs->error);
	} # if


my $dbh = OpenDB($db_host,$db,$db_user,$db_pw) ||
		die("cannot connect to db '$db' on '$db_host' as '$db_user'");

	$dbh->{RaiseError} = 1;
	$dbh->{AutoCommit} = 1;


	# TODO: read zconfig file and get sense of hot

my $cutoff = time() - ($max_hot_days * 24 * 3600);
#print STDERR "cutoff ",scalar localtime($cutoff),"\n";
	$dbh->do(qq{ DELETE FROM hot_dirs
		     WHERE stat_utc < ?},undef,
		     $cutoff);

	CloseDB($dbh);
	close(LOCK);
} # main_thing



main_thing(@ARGV);
