#!/usr/bin/perl
 
#SWAP.PL by J.Tom Germain, cgiware@cgiware.olm.net 
#September, 1996
#You are free to use & modify this script for your own purposes as long
#as it includes the credit you see on line 3, and don't sell it.
#I am not responsible for losses or injury of any kind resulting from the
#use of this script 

#####GET ARGUMENTS
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>;
}
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);}

if($filename !~ /\./){$filename .= '.rep';}
$filename =~ s/\s//g;
$dirpath = $ARGV[1];
open(FIL, "<$filename") || die "Can't open $filename\n";
@conf = <FIL>;
close(FIL);
foreach $line (@conf){
($name,$value) = split(/:/,$line);
if($name =~ /search/i){$search = $value;}
if($name =~ /replace/i){$replace = $value;}
if($name =~ /directory/i){$dirpath = $value;}
}
}

$search =~ s/(\n|\r|\t)/ /g;
$search =~ s/( +)$//;
$search =~ s/^( +)//;
$replace =~ s/(\n|\r|\t)/ /g;
$replace =~ s/( +)$//;
$replace =~ s/^( +)//;
$dirpath =~ s/\s//g;
print "\nStarting search and replace ...\n";

if($dirpath eq ""){$dirpath = '.';}
opendir(DIR, "$dirpath") || die "Can't open dirpath\n";
@files = readdir(DIR);
closedir(DIR);

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

foreach $file (@files){
open(FIL,"<$file") || next;
@data = <FIL>;
close(FIL);
if(grep(/$search/,@data)){
foreach $line (@data){
$line =~ s/$search/$replace/gi;
}
open(FIL,">$file") || next;
seek(FIL,0,0);
print FIL "@data";
close(FIL);
}
}
