#!/usr/bin/perl -w
#---------------------------------------------------------------
# Description:  This script will delete stale SessionX files.
# Author:       Neal Gamradt (ngamradt@yahoo.com)
# Project:      All EMBPerl Projects
# Created:      2004.11.21
# Modified:     2004.11.21
#---------------------------------------------------------------

my $strSessionXDir = '/var/sessionx/'; #The base folder that the sessionx files are stored in.
my $strLockfilesDir = 'lockfiles'; #The sub-directory that the sessionx lock files are in.
my $nbrMinutesStale = 2880; #Files older than this number (in minutes) will be deleted.

#Delete all of the stale lockfiles
my @arrLines = getCleanDir("$strSessionXDir$strLockfilesDir");
foreach my $strFile (@arrLines) {
	if (checkStale("$strSessionXDir$strLockfilesDir",$strFile,$nbrMinutesStale)) {
		deleteStale("$strSessionXDir$strLockfilesDir",$strFile);
	}
}

#Delete all of the stale SessionX files 
@arrLines = getCleanDir($strSessionXDir);
foreach my $strFile (@arrLines) {
	if ($strFile ne $strLockfilesDir) {
		if (checkStale($strSessionXDir,$strFile,$nbrMinutesStale)) {
			deleteStale($strSessionXDir,$strFile);
		}
	}
}

sub getCleanDir {
	my $strDir = shift;

	opendir(dhDIR,$strDir);
	my @arrLines = readdir(dhDIR);
	close(dhDIR);

	#Remove '.' and '..' directories
	shift @arrLines;
	shift @arrLines;

	return @arrLines;	
}

sub checkStale {
	my $strDir = shift;
	my $strFile = shift;
	my $nbrMinutesStale = shift;
	my $nbrSecondsStale = $nbrMinutesStale * 60;
	my $nbrCurrentTime = time;
	my $nbrAccessTime = (stat("$strDir/$strFile"))[8];

	#If the last access time with the addition of seconds stale is less than the current time, then do the following.
	if (($nbrAccessTime + $nbrSecondsStale) < $nbrCurrentTime) {
		return 1;
	}
	else {
		return 0;
	}
}

sub deleteStale {
	my $strDir = shift;
	my $strFile = shift;
	unlink("$strDir/$strFile");
	print "Deleted $strFile\n";
}
