#! /usr/bin/perl -w
#
# $Id: fileedit.pl,v 1.6 2004/03/01 08:56:58 bc Exp $
# 
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
# 
# The contents of this file are subject to the Mozilla Public License Version 
# 1.1 (the "License"); you may not use this file except in compliance with 
# the License. You may obtain a copy of the License at 
# http://www.mozilla.org/MPL/
# 
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
# 
# The Original Code is Netscape code.
#
# The Initial Developer of the Original Code is
# Netscape Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s): Bob Clary <bclary@netscape.com>
# Contributor(s): Bob Clary <http://bclary.com>
# 
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
# 
# ***** END LICENSE BLOCK *****
# Edit all files in STARTDIR directory tree matching the
# FILEREGX pattern. Replace all occurences of FROM with TO.
#
# usage: perl fileedit.pl STARTDIR FILEREGX FROM TO
# 
#

use strict;
use File::Find ();
use File::Basename;

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;


my $argsok = 0;
my $argcount = $#ARGV + 1;

#print "$argcount\n";

if ($argcount >= 3)
{
  %::editpattern = ();
  $::startdir = shift;
  $::fileregx = shift;

  my $fromregx = shift;

  if ($argcount == 4)
  {
    #print "from/to pattern on command line\n";
    my $toregx = shift;
    $::editpattern{$fromregx} = $toregx;
    $argsok = 1;
  }
  else
  {
    # fromregx is a filename
    my $file = $fromregx;

    #print "loading: file: $file\n";

    open FILE, "<$file" or die "$file could not be opened\n";
    while (<FILE>)
    {
      #print "loading: line: $_";

      my @pattern = ($_ =~ /[\s]*([^\t]+)[\t]+([^\t]+)[\s]*/);
      if ($#pattern == 1)
      {
        chomp $pattern[1];
        #print "loading: from: $pattern[0], to: $pattern[1]\n";

        $::editpattern{$pattern[0]} = $pattern[1];
      }
    }
    close FILE;
    $argsok = 1;
  }
}

if (!$argsok)
{
  print <<USAGE;
fileedit.pl v 0.22

USAGE:   fileedit.pl STARTDIR FILEREGX [FROM TO|FILE]

         Edit matching files in STARTDIR directory 
         tree matching the FILEREGX pattern.
         
         If FROM TO are specified then each file has
         all occurences of the string FROM replaced 
         with the string TO.

         If FILE is specified, it must contain a list of
         lines with each line containing a FROM TO pair
         separate by 1 or more tab characters

NOTE:    To match files with .html extension use a
         regular expression like \"\\.html\?\$\"
         
         Only files with extensions 
         .htm, .html, .xml, .xul, .xsl, .txt, .css, .js, .cgi, .map, .psp, 
         .php, .asp  will be edited.

         Any directory path containing /CVS/ will be excluded.

         All file timestamps will remain unchanged.

CAUTION: This does not backup the edited files. 
         BE CAREFUL and make backups of your files 
         before using this program.
USAGE
exit (1);
}


# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, $::startdir);
exit;


sub wanted 
{
  #print "wanted: Dir: $dir, File: $_, Pattern: $::fileregx\n";

  return if (!($_ =~ /(\.html?|\.xml|\.xul|\.xsl|\.txt|\.css|\.js|\.map|\.psp|\.php|\.asp)$/i));
  return if (($dir =~ /\/CVS$/));
  return if (!($_ =~ /$::fileregx/));
#  return unless -T $_;

  #print "wanted: matched!\n";

  my $myfile = $_;
  my $text = '';
  my $oldtext = '';
  #my $timestamp = (stat $myfile)[9];
  my $fromregx;
  my $toregx;

  open (FILE, "<$myfile") or die "unable to open $myfile for reading: $!\n";
  $text = join ("", <FILE>);
  close FILE;

  $oldtext = $text;

  foreach $fromregx (keys %::editpattern)
  {
    $toregx = $::editpattern{$fromregx};

    #print "editing: from: $fromregx, to: $toregx\n";

    $text =~ s/$fromregx/$toregx/g;
  }

  #XXXbc: Hack the problem with embedded \r in Cygwin
  #$text =~ s/\r//g;

  if ($text ne $oldtext)
  {
    open (FILE, ">$myfile") or die "unable to open $myfile for writing: $!\n";
    print FILE $text;
    close FILE;
  }

  #utime $timestamp, $timestamp, ($myfile);

}

