#/usr/bin/perl
 
if($#ARGV < 0){
	print "Enter string to search for:\n ";
	$search = <STDIN>;
	print "\nEnter string to replace it with:\n ";
	$replace = <STDIN>;
	print "\nEnter directory path to search:\n ";
	$dirpath = <STDIN>;
	$doit[0] = "$search^^$replace^^$dirpath";
	}
else{
	$filename = $ARGV[0];

	if($filename !~ /\w/){
		print "You must specify a configuration file.\n";
		print "If you wish to enter parameters manually, don't put arguments.\n";
		exit(1);}

	$dirpath = $ARGV[1];

	if($filename !~ /\./){$filename .= '.rep';}
	$filename =~ s/\s//g;

	open(FIL, "<$filename") || die "Can't open $filename\n";
	@doit = <FIL>;
	close(FIL);
	}

print "\nStarting search and replace...(Copyright 1996 Tom Germain)\n";

$count = 0;

loopz:
foreach $line (@doit){
	$line =~ s/(\n|\r|\t)//g;

	($search,$replace,$newdirpath) = split(/\^\^/,$line);
	if($newdirpath ne ""){$dirpath = $newdirpath;}

	if($dirpath eq ""){$dirpath = '.';}
	$dirpath =~ s/\s//g;

	if($dirpath !~ /(\/)$/){$dirpath .= '/';}

	print "Opening $dirpath\n";
	opendir(DIR, "$dirpath") || next;
	print "Okay\n";

	@files = readdir(DIR);
	closedir(DIR);

	@files = grep(!/^(\.|\.\.)$/,@files);

	loopy:
	foreach $file (@files){

		if(!(-f "$dirpath$file")){

			if(-d "$dirpath$file"){
				$doit[$#doit + 1] = "$search^^$replace^^$dirpath$file";
				}
			next;
			}

		open(FIL,"<$dirpath$file") || next;

		@data = ();

		@data = <FIL>;
		close(FIL);

		loopx:
		if($num = grep(/$search/,@data)){

		foreach $line (@data){
			if($line =~ s/$search/$replace/gi){$count++;}
			}

		open(FIL,">$dirpath$file") || next;
		seek(FIL,0,0);
		print FIL @data;
		close(FIL);
		} #end loopx

	} #end loopy
} #end loopz

print "\nDONE! Total matches replaced: $count\n";
