/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.tools.ant.taskdefs.optional;


import java.io.*;
import java.util.*;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.util.regexp.RegexpMatcher;
import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;

/**
 * An implementation of an ANT task for performing Regexp replacements in text files.
 * <p>
 * Note that regular expression syntax is dependent on what regexp library is installed.
 * Similarly, the substitution string may contain sub-match references if the installed
 * regexp library supports interpolation.
 * <p>
 * @author <a href="mailto:brendan@cortexebusiness.com.au">Brendan Humphreys</a>
 **/
public class RegexpReplace
    extends Task
{
    /** contains the filesets to process **/
    private final List mFileSets = new ArrayList();

    /** the regexp pattern **/
    private String mPattern;

    /** the string to substitute for matches **/
    private String mSubstitution;

    /** flag to indicate multiline matching **/
    private boolean mMultiline = false;

    /** flag to indicate case insensitive matching **/
    private boolean mIgnoreCase = false;

    /** flag to indicate if a summary is required **/
    private boolean mSummary = false;

    /** the regexp matcher used **/
    private RegexpMatcher mMatcher = RegexpMatcherFactory.getRegexpMatcher();

    ////////////////////////////////////////////////////////////////////////////
    // Setters for attributes
    ////////////////////////////////////////////////////////////////////////////

    /**
     * Adds a set of files (nested fileset attribute).
     * @param aFS the file set to add
     */
    public void addFileset(FileSet aFS)
    {
        mFileSets.add(aFS);
    }

    /**
     * set the regexp pattern
     */
    public void setPattern(String aPattern)
        throws BuildException
    {
        mPattern = aPattern;
    }

    /**
     * set the substitution string
     * @param aSubst
     */
    public void setSubstitution(String aSubst)
    {
        mSubstitution = aSubst;
    }

    /**
     * set whether or not to use multiline matching
     */
    public void setMultiline(boolean aMultiline)
    {
        mMultiline = aMultiline;
    }

    /**
     * set whether or not to use case insensitive matching
     */
    public void setIgnoreCase(boolean aIgnoreCase)
    {
        mIgnoreCase = aIgnoreCase;
    }

    /**
     * request a summary
     */
    public void setSummary(boolean aSummary) {
        mSummary = aSummary;
    }

    ////////////////////////////////////////////////////////////////////////////
    // The doers
    ////////////////////////////////////////////////////////////////////////////

    /**
     * process files specified. Will fail if any errors occurred.
     * @throws BuildException an error occurred
     **/
    public void execute()
        throws BuildException
    {
        // Check arguments
        if (mFileSets.size() == 0) {
            throw new BuildException("Must specify a nested 'fileset'.", location);
        }

        if (mPattern == null || mPattern.length() == 0) {
            throw new BuildException("Must specify a pattern.", location);
        }
        if (mSubstitution == null) {
            throw new BuildException("Must specify a substitution.", location);
        }

        mMatcher.setPattern(mPattern, mMultiline, mIgnoreCase);

        int changed = 0;

        // do the work
        final Iterator it = mFileSets.iterator();
        while (it.hasNext()) {
            final FileSet fs = (FileSet) it.next();
            final DirectoryScanner ds = fs.getDirectoryScanner(project);
            final String dir = fs.getDir(project).getAbsolutePath();
            final String [] filelist = ds.getIncludedFiles();
            for (int i = 0; i < filelist.length; i++) {
                changed += doReplace(dir + File.separator + filelist[i]);
            }
        }
        if (mSummary) {
            log("RegexpReplace modified " + changed + " files",
                Project.MSG_INFO);
        }
    }

    /**
     * perform substitution on the given file
     */
    private int doReplace(String aFileName)
        throws BuildException
    {
        try {
            final File src = new File(aFileName);
            final File temp = File.createTempFile("regexpreplace", null);

            final BufferedReader br = new BufferedReader(new FileReader(src));
            final BufferedWriter bw = new BufferedWriter(new FileWriter(temp));

            // read the entire file into a StringBuffer
            final StringBuffer tmpBuf = new StringBuffer((int)(src.length()));
            int readChar = 0;
            while (true) {
                readChar = br.read();
                if (readChar < 0) {
                    break;
                }
                tmpBuf.append((char)readChar);
            }
            // convert to a String
            final String buf = tmpBuf.toString();

            // do the substitution
            final String newString = mMatcher.substitute(buf, mSubstitution);

            final boolean changes = !newString.equals(buf);
            if (changes) {
                bw.write(newString, 0, newString.length());
                bw.flush();
            }

            bw.close();
            br.close();

            // If there were changes, move the new one to the old one;
            // otherwise, delete the new one
            if (changes) {
                log("RegexpReplace modified" + aFileName, Project.MSG_VERBOSE);
                src.delete();
                temp.renameTo(src);
                return 1;
            }
            else {
                temp.delete();
                return 0;
            }
       }
        catch (IOException ioe) {
            throw new BuildException(ioe, location);
        }
    }
}
