#!C:\Perl\bin
#
# search for a file in all subdirectories of specificed folder
#
use File::Find;
# 

$dir = 'C:\thl-repos\development'; # 'C:\thl-repos\staging\www';
$stringToFind = "";

if ($#ARGV == -1 || $#ARGV > 2 ) {
	print "usage: FindFiles.pl filename loc=dirLocation{opt.} str=stringToFind{opt.} \n";
	print "\t-- with just a filename will search for files with that name or containing that string in the predefined location, $dir\n";
	print "\t-- with dirLocation argument will search in that location\n";
	print "\t-- with stringToFind argument will return files with certain name and containing stringToFind in location\n";
    exit;
}

$nameToFind = $ARGV[0];
if ($#ARGV > 0 ) {
	for($n = 1; $n < $#ARGV + 1; $n++) {
		if($ARGV[$n] =~ /loc=(\S+)/) { $dir = $1; }
		if($ARGV[$n] =~ /str=(\S+)/) { $stringToFind = $1; }
	}
}

print "\*************************************************\nFinding files ";
if(length($stringToFind) > 0) { print "containing \"$stringToFind\" and \n";}
print "whose name contains, \"" . $nameToFind . "\", \nin directory: " . $dir . "\n------------------------------------------------\n";
find(\&wanted, $dir);
print "\n------------------------------------------------\n";

sub wanted {
    local($dir);
    local(@lines);
    local($line);
    local($file);
    local($subdir);

    $dir = $_[0];
    $file = $_;
    # check if it's a file
    unless(-d $file) {
		if($file =~ /$nameToFind/) {
			$fnm = $File::Find::name;
			$fnm =~ s/\//\\/g;
			$foundText = findText($fnm,$stringToFind);
			if($foundText == 1) {
				print $fnm . "\n";
			}
		}
    }
}

sub findText {
	my $fn = $_[0];
	my $stf = $_[1];
	$retval = 0;
	if(length($stf) == 0) {	$retval =  1;	}
	open(F,$fn);
	@list=<F>;
	close F;
	@f=grep /$stf/,@list;
	if($#f > -1) { $retval = 1;}
	if($fn =~ /\.svn/) {$retval = 0;}
	return $retval;
}

