/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2003 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 acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" 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" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * 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.jetspeed.util.file;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.File;

/**
* Task to merge files to create the database script
*
* @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
* @version $Id: MergeFiles.java,v 1.3 2003/05/07 15:34:56 morciuch Exp $
*/
public class MergeFiles
{
    protected static List files;
    protected static String dest_file = null;

    public static boolean verbose = false;

    protected static ArrayList baseArray = new ArrayList(1024);
    protected static String lineSeparator = System.getProperty("line.separator", "\r\n");

    public static void main(String[] args) throws Exception
    {
        MergeFiles main=new MergeFiles();

        try
        {
            if(args.length < 2)
            {
                System.out.println("Usage: java MergeFiles [scratch/drop] c:/temp/all.sql c:/temp/dbpsml.sql c:/temp/populate.sql .... c:/temp/File(n)");
                System.out.println("Usage: If scratch is specified then all sql statements starting with DROP will be overlooked.");
                System.out.println("Usage: If drop is specified then only sql statements starting with DROP will be added.");
                System.out.println("Usage: All the files listed after c:/temp/all.sql will be added to c:/temp/all.sql");
                throw new Exception("Incorrect number of arguments supplied");
            }
            int file_index = 0;
            boolean db_from_scratch = false;
            boolean db_drop = false;

            if (args[0].equals("scratch"))
            {
                file_index = 1;
                db_from_scratch = true;
            }
            else if (args[0].equals("drop"))
            {
                file_index = 1;
                db_drop = true;                
            }

            files = new Vector(args.length - 1 - file_index);
            dest_file = args[file_index];
            for (int index = (file_index + 1); index < args.length; index++)
            {
                files.add(args[index]);
            }

            for (int index = 0; index < files.size(); index++)
            {
                BufferedReader reader =  new BufferedReader(new FileReader((String)files.get(index)));
                String line = null;
                int idx = 0;
                while((line = reader.readLine()) != null)
                {   if (line.startsWith("#"))
                    {
                        continue;
                    }
                    if (db_from_scratch)
                    {
                        if (!(line.startsWith("DROP") || 
                              line.startsWith("drop") || 
                              line.startsWith("Drop")))
                        {
                            baseArray.add(idx, line);
                            idx++;
                        }
                    }
                    else if (db_drop)
                    {
                        if ( (line.startsWith("DROP") || 
                              line.startsWith("drop") || 
                              line.startsWith("Drop")))
                        {
                            baseArray.add(idx, line);
                            idx++;
                        }                        
                    }
                    else
                    {
                        baseArray.add(idx, line);
                        idx++;
                    }
                    if(verbose)
                        System.out.println("While reading baseArray["+idx+"] = " + line);
                }
                reader.close();
            }
            if(verbose)
                System.out.println("\nMerge Files\n");

            baseArray.add("commit;");
            baseArray.trimToSize();

            main.writeToFile();

        }
        catch(FileNotFoundException ex)
        {
            System.err.println(ex.getMessage());
        }
        catch(IOException ex)
        {
            System.err.println(ex.getMessage());
        }
        catch(SecurityException ex)
        {
            System.err.println(ex.getMessage());
        }
    }

    public void writeToFile() throws FileNotFoundException, IOException
    {
        FileOutputStream writer = null;
        try
        {
            writer = new FileOutputStream(dest_file);
        }
        catch (FileNotFoundException ex)
        {
            File file = new File(dest_file);
            writer = new FileOutputStream(file.getPath(), false);
        }
        writer.flush();
        for (int i = 0; i < baseArray.size(); i++)
        {
            if(verbose)
                System.out.println("While writing baseArray["+i+"] = " + baseArray.get(i));
            writer.write(((String)baseArray.get(i)).getBytes());
            writer.write(lineSeparator.getBytes());
            writer.flush();
        }
        writer.close();

    }


}

