#****************************************************************************
# Name:		FileLockSmith.pl
# By:		Robert Spitzer
# Email:	robert.spitzer@ngc.com
#
# The following script closes any file locks for a given file.  If any open
# connections are found, they will be reported to standard output.
#
# Usage:	FileLockSmith [server name] [fully qualified file name]
#
# Version:	1.0.1
# Created:	10/08/01	Revised:	00/00/00
#****************************************************************************
# Modules used by this script
use File::Basename;
use Win32::Lanman;

# If no arguements are provided, print out help information.
if($ARGV[0] eq "/?" || @ARGV < 2) { Usage(); }

# If  arguments are provided, run the script.
else {
	# Variables used by this script
	$Counter = 0;
	$ServerName = $ARGV[0];
	
	$FilePath = dirname($ARGV[1]); # Extract filename
	$FileName = basename($ARGV[1]); # Extract directory name
		
	$FileName =~ tr/A-Z/a-z/;  # Convert the filename to lowercase letters
	
	# Enumerate file handles on the server
	
	if (!Win32::Lanman::NetFileEnum("\\\\$ServerName", $FilePath, '', \@FileHandles)) {
		$ErrorCode = Win32::Lanman::GetLastError();
		print "Error enumerating files on $ServerName\n";
		print "Error Code: $ErrorCode\n\n";
		exit 1;
	}
	
	# Close any open file locks that matches the filename
	foreach $FileHandle (@FileHandles) {
		@keys = keys(%$FileHandle);
		
		$PathName = ${$FileHandle}{"pathname"};
		$PathName =~ tr/A-Z/a-z/;  # Convert the filename to lowercase letters
	
		if ($PathName =~ /$FileName/) {
			$Counter++;
			$UserName = ${$FileHandle}{"username"};
			$FileID = ${$FileHandle}{"id"};
			
			print "Closing file lock of user: $UserName on $FilePath\\$FileName\n";
			
			if (!Win32::Lanman::NetFileClose("\\\\$ServerName", $FileID)) {
				$ErrorCode = Win32::Lanman::GetLastError();
				print "Error closing file lock of user: $UserName on $FilePath\\$FileName\n";
				print "Error code: $ErrorCode\n\n";
			}
		}
	}
	
	if ($Counter == 0) {
		print "No file locks detected for $FilePath\\$FileName\n";
	}
}

#****************************************************************************
sub Usage { 

print <<USAGE
	
FileLockSmith v1.0.1
Written by: Robert Spitzer

The following script closes any file locks for a given file.  If any
open connections are found, they will be reported to standard output.

Usage: FileLockSmith [server name] [fully qualified file name]
	
USAGE

}