#!/usr/local/bin/perl  

if (@ARGV == 0 || @ARGV == 1 || @ARGV == 2) {
        die "usage: replace_file_recur FILENAME OLDPATTERN NEWPATTERN\n";
}

$name_to_grep = shift(@ARGV);
$old_pattern  = shift(@ARGV);
$new_pattern  = shift(@ARGV);
$rename_param = ".old";

&dodir('.');

sub dodir {
    local($dir,$nlink) = @_;
    local($dev,$ino,$mode,$subcount);

    # At the top level, we need to find nlink ourselves.

    ($dev,$ino,$mode,$nlink) = stat('.') unless $nlink;

    # Get the list of files in the current directory.

    opendir(DIR,'.') || die "Can't open $dir";
    local(@filenames) = readdir(DIR);
    closedir(DIR);

    if ($nlink == 2) {        # This dir has no subdirectories.
	for (@filenames) {
	    next if $_ eq '.';
	    next if $_ eq '..';
	    if ($_ eq $name_to_grep )  {
	      &replace_pattern($_, $old_pattern, $new_pattern);
	      print "working on $dir/$_\n";
	    }
	}
    }
    else {                    # This dir has subdirectories.
	$subcount = $nlink - 2;
	for (@filenames) {
	    next if $_ eq '.';
	    next if $_ eq '..';
	    $name = "$dir/$_";
	    if ($_ eq $name_to_grep )  {
	      &replace_pattern($_, $old_pattern, $new_pattern);
	      print "working on ", $name, "\n";
	    }
	    next if $subcount == 0;    # Seen all the subdirs?

	    # Get link count and check for directoriness.

	    ($dev,$ino,$mode,$nlink) = lstat($_);
	    next unless -d _;

	    # It really is a directory, so do it recursively.

	    chdir $_ || die "Can't cd to $name";
	    &dodir($name,$nlink);
	    chdir '..';
	    --$subcount;
	}
    }
}


sub replace_pattern {
    local($local_file, $local_old, $local_new) = @_;

    $temp_file = $local_file . $rename_param;
    system("cp $local_file $temp_file");

    open(FILE, ">$local_file");
    open(FILE2, "$temp_file");

    while ($a = <FILE2>) {
  	$a =~ s/\b\s$local_old\s\b/$local_new/g;
 	print FILE $a;
    }
    close(FILE);
    close(FILE2);
}