/***************************************************************************
    Copyright          : (C) 2002 by Neoworks Limited. All rights reserved
    URL                : http://www.neoworks.com
 ***************************************************************************/
/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;

/**
 * Configure JukeX for deployment
 *
 * @author Nigel Atkinson (<a href="mailto:nigel@neoworks.com">nigel@neoworks.com</a>)
 */
public class ConfigureJukeX
{
	private static String castServerName = null;
	private static String castServerSourcePort = null;
	private static String castServerListenerPort = null;
	private static String castStreamName = null;
	private static String castStreamDescription = null;
	private static String castServerPassword = null;
	private static String castStreamGenre = null;
	private static String castStreamBitrate = null;
	private static String castStreamURL = null;
	private static String dbURL = null;
	private static String dbUser = null;
	private static String dbPassword = null;
	private static String dbConnections = "20";

	private static String webXMLFilePath = null;
	private static String dbPoolXMLFilePath = null;

	/**
	 * Entry point
	 *
	 * @param args the command line arguments
	 */
	public static void main(String[] args)
	{
		System.out.println("JukeX Configuration Tool");
		if (args.length > 1)
		{
			webXMLFilePath = args[0];
			dbPoolXMLFilePath = args[1];
			System.out.println("Writing configuration files:");
			System.out.println("\tweb.xml: " + webXMLFilePath);
			System.out.println("\tdatabasepool.xml: " + dbPoolXMLFilePath);
		} else {
			System.err.println("Usage: java ConfigureJukeX <webXMLPath> <databasePoolXMLPath>");
			System.exit(0);
		}
		System.out.println("\nYou will REQUIRE the following information:");
		System.out.println("\tIcecast/Shoutcast server name");
		System.out.println("\tIcecast/Shoutcast server source connection port");
		System.out.println("\tIcecast/Shoutcast server listener connection port");
		System.out.println("\tIcecast/Shoutcast server password");
		System.out.println("\tDatabase connection URL (e.g. 'jdbc:mysql://servername/JukeX')");
		System.out.println("\tDatabase user");
		System.out.println("\tDatabase password");
		System.out.print("Would you like to proceed (n to leave configuration unchanged)? (y/n) ");
		System.out.flush();
		BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
		String input = null;
		boolean validData = false;
		try {
			while ((input = inputReader.readLine()) == null){}
			if (input.toLowerCase().startsWith("y"))
			{
				System.out.println("");
				while (!validData){
					System.out.print("Icecast/Shoutcast server name: ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					if (!input.equals(""))
					{
						castServerName = input;
						validData = true;
					}
				}
				validData = false;
				while (!validData){
					System.out.print("Icecast/Shoutcast server source connection port: ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					try {
						Integer.parseInt(input);
						castServerSourcePort = input;
						validData = true;
					} catch (NumberFormatException nfe) {
						validData = false;
					}
				}
				validData = false;
				while (!validData){
					System.out.print("Icecast/Shoutcast server listener connection port: ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					try {
						Integer.parseInt(input);
						castServerListenerPort = input;
						validData = true;
					} catch (NumberFormatException nfe) {
						validData = false;
					}
				}
				System.out.print("Icecast/Shoutcast server stream name (if this is not specified the default stream will be used): ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				castStreamName = input;
				System.out.print("Icecast/Shoutcast server stream description (optional): ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				castStreamDescription = input;
				System.out.print("Icecast/Shoutcast server password: ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				castServerPassword = input;
				System.out.print("Icecast/Shoutcast stream genre description: ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				castStreamGenre = input;
				System.out.print("Icecast/Shoutcast stream URL: ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				castStreamURL = input;
				validData = false;
				while (!validData){
					System.out.print("Icecast/Shoutcast stream bitrate indication: ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					try {
						Integer.parseInt(input);
						castStreamBitrate = input;
						validData = true;
					} catch (NumberFormatException nfe) {
						validData = false;
					}
				}
				validData = false;
				while (!validData){
					System.out.print("Database connection URL (e.g. 'jdbc:mysql://servername/JukeX'): ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					if (!input.equals(""))
					{
						dbURL = input;
						validData = true;
					}
				}
				System.out.print("Database user: ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				dbUser = input;
				System.out.print("Database password: ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				dbPassword = input;
				validData = false;
				while (!validData){
					System.out.print("Maximum database connections supported (defaults to 20): ");
					System.out.flush();
					while ((input = inputReader.readLine()) == null){}
					if (input.length() == 0)
					{
						validData = true;
					} else {
						try {
							Integer.parseInt(input);
							dbConnections = input;
							validData = true;
						} catch (NumberFormatException nfe) {
							validData = false;
						}
					}
				}
				System.out.println("Information collected:");
				System.out.println("\tIcecast/Shoutcast server name: " + castServerName);
				System.out.println("\tIcecast/Shoutcast server source connection port: " + castServerSourcePort);
				System.out.println("\tIcecast/Shoutcast server listener connection port: " + castServerListenerPort);
				System.out.println("\tIcecast/Shoutcast server stream name: " + castStreamName);
				System.out.println("\tIcecast/Shoutcast server stream description: " + castStreamDescription);
				System.out.println("\tIcecast/Shoutcast server password: " + castServerPassword);
				System.out.println("\tIcecast/Shoutcast stream genre description: " + castStreamGenre);
				System.out.println("\tIcecast/Shoutcast stream genre description: " + castStreamURL);
				System.out.println("\tIcecast/Shoutcast stream bitrate indication: " + castStreamBitrate);
				System.out.println("\tDatabase connection URL: " + dbURL);
				System.out.println("\tDatabase user: " + dbUser);
				System.out.println("\tDatabase password: " + dbPassword);
				System.out.println("\tMaximum database connections supported: " + dbConnections);
				System.out.println("");
				System.out.print("Do you wish to write the configuration files? (y/n) ");
				System.out.flush();
				while ((input = inputReader.readLine()) == null){}
				if (input.startsWith("y"))
				{
					System.out.println("Writing configuration files...");
					File webXMLFile = null;
					File webXMLTempl = null;
					FileReader webXMLFileReader = null;
					String templateWebXMLFileContents = null;
					char [] templateWebXMLFileContentsArray = null;
					try {
						webXMLTempl = new File(webXMLFilePath + ".tmpl");
						webXMLFileReader = new FileReader(webXMLTempl);
						templateWebXMLFileContentsArray = new char[(int)webXMLTempl.length()];
						int charsRead = webXMLFileReader.read(templateWebXMLFileContentsArray, 0, (int)webXMLTempl.length());
						templateWebXMLFileContents = new String (templateWebXMLFileContentsArray);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutServerName%",castServerName);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutServerSourcePort%",castServerSourcePort);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutServerListenerPort%",castServerListenerPort);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutServerPassword%",castServerPassword);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutStreamName%",castStreamName);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutStreamDescription%",castStreamDescription);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutStreamGenre%",castStreamGenre);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutStreamBitrate%",castStreamBitrate);
						templateWebXMLFileContents = templateWebXMLFileContents.replaceFirst("%shoutStreamURL%",castStreamURL);
						/*System.out.println("File contents:");
						System.out.println(templateWebXMLFileContents);*/
						webXMLFile = new File(webXMLFilePath);
						if (!webXMLFile.createNewFile())
						{
							webXMLFile.renameTo(new File(webXMLFilePath + ".old"));
							webXMLFile = new File (webXMLFilePath);
							if (!webXMLFile.createNewFile())
							{
								System.err.println("Cannot create web.xml file");
								System.exit(-1);
							}
						}
						FileWriter webXMLFileWriter = new FileWriter(webXMLFile);
						webXMLFileWriter.write(templateWebXMLFileContents);
						webXMLFileWriter.close();
					} catch (Exception e) {
						System.err.println("Cannot write web.xml");
						e.printStackTrace();
					}
					File dbPoolXMLFile = null;
					File dbPoolXMLTempl = null;
					FileReader dbPoolXMLFileReader = null;
					String templateDbPoolXMLFileContents = null;
					char [] templateDbPoolXMLFileContentsArray = null;
					try {
						dbPoolXMLTempl = new File(dbPoolXMLFilePath + ".tmpl");
						dbPoolXMLFileReader = new FileReader(dbPoolXMLTempl);
						templateDbPoolXMLFileContentsArray = new char[(int)dbPoolXMLTempl.length()];
						int charsRead = dbPoolXMLFileReader.read(templateDbPoolXMLFileContentsArray, 0, (int)dbPoolXMLTempl.length());
						templateDbPoolXMLFileContents = new String (templateDbPoolXMLFileContentsArray);
						templateDbPoolXMLFileContents = templateDbPoolXMLFileContents.replaceFirst("%dbURL%",dbURL);
						templateDbPoolXMLFileContents = templateDbPoolXMLFileContents.replaceFirst("%dbUser%",dbUser);
						templateDbPoolXMLFileContents = templateDbPoolXMLFileContents.replaceFirst("%dbPassword%",dbPassword);
						templateDbPoolXMLFileContents = templateDbPoolXMLFileContents.replaceFirst("%dbConnections%",dbConnections);
						/*System.out.println("File contents:");
						System.out.println(templateDbPoolXMLFileContents);*/
						dbPoolXMLFile = new File(dbPoolXMLFilePath);
						if (!dbPoolXMLFile.createNewFile())
						{
							dbPoolXMLFile.renameTo(new File(dbPoolXMLFilePath + ".old"));
							dbPoolXMLFile = new File (dbPoolXMLFilePath);
							if (!dbPoolXMLFile.createNewFile())
							{
								System.err.println("Cannot create web.xml file");
								System.exit(-1);
							}
						}
						FileWriter dbPoolXMLFileWriter = new FileWriter(dbPoolXMLFile);
						dbPoolXMLFileWriter.write(templateDbPoolXMLFileContents);
						dbPoolXMLFileWriter.close();
					} catch (Exception e) {
						System.err.println("Cannot write databasepool.xml");
						e.printStackTrace();
					}
				} else {
					System.out.println("Aborting configuration");
					File webXMLFile = new File (webXMLFilePath);
					File dbPoolXMLFile = new File (dbPoolXMLFilePath);
					if (!webXMLFile.exists() || !dbPoolXMLFile.exists())
					{
						System.out.println("WARNING: Configuration files are incomplete.");
						System.exit(-1);
					}
				}
			} else {
				System.out.println("Skipping configuration");
				File webXMLFile = new File (webXMLFilePath);
				File dbPoolXMLFile = new File (dbPoolXMLFilePath);
				if (!webXMLFile.exists() || !dbPoolXMLFile.exists())
				{
					System.out.println("WARNING: Configuration files are incomplete.");
					System.exit(-1);
				}
			}
			System.out.println("Done");
		} catch (IOException ioe) {
			System.err.println("I/O Error");
		}
	}
}
