/***********************************************************************
 * 
 *  Copyright (C) 2006 Novell, Inc. All Rights Reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; version 2.1
 *  of the License.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, Novell, Inc.
 * 
 *  To contact Novell about this file by physical or electronic mail, 
 *  you may find current contact information at www.novell.com.
 * 
 *  Author: Juan Carlos Luciani <jluciani@novell.com>
 *  
 ***********************************************************************/

package MungeCryptoPropertiesFilePath;

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

/**
 * Summary description for Program
 */
public class Program
{
	final static int ERROR_NO_ERROR						= 0;
	final static int ERROR_INVALID_NUMBER_OF_PARAMS		= -1;
	final static int ERROR_MISSING_INPUT_FILE			= -2;
	final static int ERROR_OUTPUT_COPY_FAILED			= -3;
	final static int ERROR_IO_EXCEPTION					= -4;
	final static int ERROR_BAD_INPUT_FILE_PARAM			= -5;
	final static int ERROR_BAD_OUTPUT_FILE_PARAM		= -6;
	final static int ERROR_MISSING_INPUT_FILE_PARAM		= -7;
	final static int ERROR_MISSING_OUTPUT_FILE_PARAM	= -8;
	final static int ERROR_CANNOT_READ_FILE				= -9;
	final static int ERROR_CANNOT_CREATE_FILE			= -10;

	final static String INPUT_FILE_PARAM	= "input=";
	final static String OUTPUT_FILE_PARAM	= "output=";
	final static String FILE_KEY			= "org.apache.ws.security.crypto.merlin.file=";

	File			fileInput;
	File			fileOutput;
	File			file;
	FileWriter		fw;
	String			sInput;
	String			sOutput;

	public static void main(String[] args)
	{
		Program p = new Program(args);
	}

	Program(String[] args)
	{
		int rc = ERROR_NO_ERROR;

		fileInput = null;
		fileOutput = null;

		try
		{
			file = new File("c:\\test5.log");
			fw = new FileWriter(file);

			log("Here we go: " + args.length);
			for (int i = 0; i < args.length; i++)
			{
				log("Arg " + i + " = " + args[i]);
			}

			// Process the arguments
			if (ERROR_NO_ERROR == (rc = processArgs(args)))
			{
				// Process the file
				rc = createOutputFile();
			}

		}
		catch (IOException e)
		{
			rc = ERROR_IO_EXCEPTION;
		}
		finally
		{
			try
			{
				log("return code = " + rc);
				fw.flush();
				fw.close();
			}
			catch (Exception e1)
			{
			}
		}
		System.exit(rc);
	}

	int processArgs(String[] args)
	{
		int i;

		// Validate the number of parameters
		if (args.length != 2)
		{
			return ERROR_INVALID_NUMBER_OF_PARAMS;
		}

		for (i = 0; i < args.length; i++)
		{
			log("arg[" + i + "] = " +args[i]);

			if (args[i].startsWith(INPUT_FILE_PARAM))
			{
				// Make sure it is more than the param tag
				if (args[i].length() <= INPUT_FILE_PARAM.length())
				{
					return ERROR_BAD_INPUT_FILE_PARAM;
				}

				sInput = args[i].substring(INPUT_FILE_PARAM.length()).trim();
				fileInput = new File(sInput);

				// Make sure the input file can be found
				if (!fileInput.exists())
				{
					log(ERROR_MISSING_INPUT_FILE, sInput);
					return ERROR_MISSING_INPUT_FILE;
				}
			}

			else if (args[i].startsWith(OUTPUT_FILE_PARAM))
			{
				// Make sure it is more than the param tag
				if (args[i].length() <= OUTPUT_FILE_PARAM.length())
				{
					return ERROR_BAD_OUTPUT_FILE_PARAM;
				}

				sOutput = args[i].substring(OUTPUT_FILE_PARAM.length()).trim();
				fileOutput = new File(sOutput);
			}
		}

		// Make sure we got an input file
		if (null == fileInput)
		{
			return ERROR_MISSING_INPUT_FILE_PARAM;
		}

		// Make sure we got an output file
		if (null == fileOutput)
		{
			return ERROR_MISSING_OUTPUT_FILE_PARAM;
		}

		return ERROR_NO_ERROR;
	}

	int createOutputFile()
	{
		LineNumberReader lnr = null;
		FileWriter fwOutput = null;
		String sLineTemplate;
		String sLineOutput;
		int iSearchFor;

		try
		{
			// Open the file
			lnr = new LineNumberReader(new FileReader(fileInput));
		}
		catch (Exception e)
		{
			return ERROR_CANNOT_READ_FILE;
		}

		try
		{
			fwOutput = new FileWriter(fileOutput);
		}
		catch (Exception e)
		{
			return ERROR_CANNOT_CREATE_FILE;
		}
		try
		{
			// For each line of text in the template file...
			while (null != (sLineTemplate = lnr.readLine()))
			{
				sLineOutput = sLineTemplate;
				log("<-- " + sLineOutput);

				if (sLineOutput.trim().startsWith(FILE_KEY))
				{
					// Replace all instances of the line separator on the line
					while (-1 != (iSearchFor = sLineOutput.indexOf("\\")))
					{
						log("replacing \\ at position " + iSearchFor + " with //");
						sLineOutput = sLineOutput.substring(0, iSearchFor) + "//" +
								sLineOutput.substring(iSearchFor + 1);
					}
				}
				try
				{
					fwOutput.write(sLineOutput + "\r\n");
					log("--> " + sLineOutput);
				}
				catch (Exception e)
				{
					return -42;
				}
			}

			// Clean up
			fwOutput.flush();
			fwOutput.close();
			lnr.close();
		}
		catch (Exception e)
		{
			return ERROR_OUTPUT_COPY_FAILED;
		}
		return ERROR_NO_ERROR;
	}

	void log(int err)
	{
		log(err, null);
	}

	void log(int err, String s)
	{
		String sMessage = "";

		switch (err)
		{
			case ERROR_NO_ERROR:
				sMessage = "No error";
				break;
			case ERROR_INVALID_NUMBER_OF_PARAMS:
				sMessage = "Invalid number of parameters: 2 expected";
				break;

			case ERROR_MISSING_INPUT_FILE:
				sMessage = "Invalid number of parameters: 2 expected";
				break;

			case ERROR_OUTPUT_COPY_FAILED:
				sMessage = "Unable to create output file";
				break;

			case ERROR_IO_EXCEPTION:
				sMessage = "IOException";
				break;

			case ERROR_BAD_INPUT_FILE_PARAM:
				sMessage = "Invalid input file parameter";
				break;

			case ERROR_BAD_OUTPUT_FILE_PARAM:
				sMessage = "Invalid output file parameter";
				break;

			case ERROR_MISSING_INPUT_FILE_PARAM:
				sMessage = "Missing input file parameter";
				break;

			case ERROR_MISSING_OUTPUT_FILE_PARAM:
				sMessage = "Missing output file parameter";
				break;

			case ERROR_CANNOT_READ_FILE:
				sMessage = "Cannot read file";
				break;

			case ERROR_CANNOT_CREATE_FILE:
				sMessage = "Cannot create file";
				break;

			default:
				sMessage = "Unknown error: " + err;
				break;
		}

		if (null != s)
		{
			sMessage = sMessage + s;
		}
		log(sMessage);
	}

	void log(String s)
	{
		try
		{
			fw.write(this.getClass().getName() + ": " + s + "\r\n");
		}
		catch (IOException ioe)
		{
		}
	}
}