#!/usr/bin/perl

$/="\r"; # Mac text file 
open (GR, "/Users/jamie/Desktop/GreatRenaming.csv");

while (<GR>) {
    chomp;
    my($oldpackage, $classname, $newpackage, $newdir) = split(',', $_);
    #print "$oldpackage|$classname|$newpackage|$newdir\n";
    
    $old_fq = $oldpackage . '.' . $classname;
    $new_fq = $newpackage . '.' . $classname;
    $renamings{$old_fq} = $new_fq;
}
close (GR);

#&dumphash(\%renamings);

@files_to_fix = ('struts-config.xml', 'struts-admin.xml');
#@files_to_fix = ('struts-config.xml');

foreach $filename (@files_to_fix) {
    my($oldpath) = "/Users/jamie/Code/WFI/a/WebRoot/WEB-INF/$filename";
    open(OLD, $oldpath) or die "can't open $oldpath";
    my(@filelines) = <OLD>;
    close(OLD);
    my($filetext) = join('',@filelines);
    
    my($newpath) = "/Users/jamie/Code/WFI/a/WebRoot/WEB-INF/$filename-new";
    open(NEW, "> $newpath") or die "can't open $newpath";
    print NEW &hashreplace($filetext, \%renamings) . "\n";
    close (NEW);
}

exit;


sub dumphash {
    my($hash) = @_;
    #my(%h) = %{$hash};
    foreach $key ( keys( %{$hash} )) {
	print "'$key' -> '" . $hash->{$key} . "'\n";
    }
}

sub hashreplace {
    my($textfile, $renamehash) = @_;
    foreach $oldstr ( keys( %{$renamehash} )) {
	my($newstr) = $renamehash->{$oldstr};
	#print "replacing $oldstr\n";
	$textfile =~ s/$oldstr/$newstr/gs;
    }
    return $textfile;
}
