#!/usr/bin/env perl
#
# Simple script to replace text in a bunch of files.
# Useful if the contact email for a whole website has changed
# or to remove ugly frontpage tags.
#
# The license for this GPL software can be found in gpl.txt, or through www.gnu.org
# 
# Author: Erik Costlow (erik@uhacc.net)
# Website: http://www.costlowcorp.com
# Version: 0.1
# Date: April 8, 2004
#

use strict;
use File::Find;

if(!$ARGV[0]){
	print " Normal usage: $0 \"what to replace\" \"replace with this\"\n";
	print "   Enter the phrase to replace: ";
	$ARGV[0] = <STDIN>;
	chomp($ARGV[0]);
	print "   Enter the phrase to replace it with: ";
	$ARGV[1] = <STDIN>;
	chomp($ARGV[1]);
	
}
print "Searching for: ".$ARGV[0]."\nReplacing with: $ARGV[1]\n\n";
find(\&wanted,"./");

print "\nFinished\n";

# Windows users don't like when the window just closes
if($^O eq "MSWin32"){
	print "Press Enter";
	while(<> ne "\n"){};
}

sub wanted{
	(-f $_ && -w $_ && -T $_) or return;
	my $file=$_;
	my $found = 0; # If the string was found in $file
	print "Searching $file.\n";
	open(INFILE,$file) or (print "Could not open $file for reading: $!\n" and return);
	my @text=<INFILE>;
	close(INFILE);
	for(my $x=0;$x<=$#text;$x++){
		$text[$x]=~s/$ARGV[0]/$ARGV[1]/ig and $found = 1 and
			print " -Found in $file (line ".($x+1).")\n";
	}
	if($found){
		open(OUTFILE,">$file") or (print "Unable to open $file for writing: $!\n\t$file must be changed manually\n." and return);
		foreach(@text){
			print OUTFILE $_;
		}
		close(OUTFILE);
	}
}

