#!/usr/bin/perl
#
# (C) Copyright IBM Corp. 2001
#
# $Id: jreplace,v 1.3 2002/08/19 17:59:37 dgrove-oss Exp $
#
# @author Perry Cheng

# Search *.java source files in $RVM_ROOT/rvm for specified pattern and replace with the new string.
#
# Usage: jreplace <perl-pattern> <replacement>


# Perform string replacement on java files
# 
my $filePattern = "\\A.*\\.java\\Z";

# We expect exactly two arguments.
#
if ($#ARGV != 1) {
    print "Usage: jreplace <perl-pattern> <replacement>\n";
    die;
}
my $pattern = shift @ARGV;
my $replace = shift @ARGV;

# Traverse the given directory recursively
#
sub traverse {
  my $dir = pop @_;
  local *DH;
  opendir(DH, $dir);
  my @dirEntries = readdir(DH);
  closedir(DH);
  # print "Traversing $dir\n";
  for (@dirEntries) {
    my $entry = $_;
    my $fullEntry = $dir . "/" . $_;
    if ($entry eq "." || $entry eq "..") { next; }
    if (-d $fullEntry) { traverse($fullEntry); }
    if (-f $fullEntry) { replace($fullEntry); }
  }
}

# Perform the replacement on given file
#
sub replace {
  my $file = pop @_;
  if ($file =~ /$filePattern/) {
      open (FH, $file);
      my @lines = <FH>;
      close(FH);
      my @newlines;
      my $changed = 0;
      while (@lines) {
	  my $line = shift(@lines);
	  if ($line =~ s/$pattern/$replace/) { $changed++; }
	  push @newlines, $line;
      }
      if ($changed > 0) {
	  print "Changed $changed occurrences in $file\n";
	  open (FH, ">" . $file);
	  print FH @newlines;
	  close(FH);
      }
  }
}

# Start at $RVM_ROOT/rvm just like jfind
#
my $start = $ENV{"RVM_ROOT"} . "/rvm";
print $start. "\n";
$start = `pwd`;
chop($start);
traverse($start);
