/* ===============================================================================
 *
 * Part of the InfoGlue Content Management Platform (www.infoglue.org)
 *
 * ===============================================================================
 *
 *  Copyright (C)
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2, as published by the
 * Free Software Foundation. See the file LICENSE.html for more information.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
 * Place, Suite 330 / Boston, MA 02111-1307 / USA.
 *
 * ===============================================================================
 */

package org.infoglue.cmsinstaller;

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

public class Uninstaller
{
	/**
	 * This is the entry point for the uninstaller.
	 */
	
	public static void main(String[] args)
	{
		Logger.logInfo("******************************************");
		Logger.logInfo("* Welcome to the uninstaller of infoglue *");
		Logger.logInfo("******************************************");
		
		Uninstaller uninstaller = new Uninstaller();
		uninstaller.uninstall();
	}
	
	
	/**
	 * Unistaller constructor
	 */
	
	public Uninstaller()
	{
	}
	

	/**
	 * This is the method that creates the menu option in the start-menu but of 
	 * course only if it's a windows-machine. If linux the kiddies know the 
	 * way of the beast or soon learn to. Got to check the possibilities later.
	 */
	
	public void createStartMenuItems(List removableDirectories, String dbUrl, String databaseServer, String driverName, String tomcatHomePath, String dbName, String hostName) throws Exception
	{
		String operativeSystemName = System.getProperty("os.name");
		Logger.logInfo("operativeSystemName:" + operativeSystemName);
		
		if(operativeSystemName.toLowerCase().indexOf("windows") > -1)
		{
			String userHomePath = System.getProperty("user.home");
			Logger.logInfo("userHomePath:" + userHomePath);

			String startMenuFolderPath = userHomePath + File.separator + "Start Menu" + File.separator + "Programs" + File.separator + "InfoGlue";
			File startMenuFolder = new File(startMenuFolderPath);
			startMenuFolder.mkdirs();
			
			System.err.println("Copying file: " + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "Uninstaller.class");
	    	File classFile = new File(startMenuFolder + File.separator + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller");
	    	classFile.mkdirs();
	    	copyInputStream(new FileInputStream("org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "Uninstaller.class"), new BufferedOutputStream(new FileOutputStream(classFile.getPath() + File.separator + "Uninstaller.class")));
			
			System.err.println("Copying file: " + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "MySQLDatabaseCommander.class");
	    	copyInputStream(new FileInputStream("org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "MySQLDatabaseCommander.class"), new BufferedOutputStream(new FileOutputStream(classFile.getPath() + File.separator + "MySQLDatabaseCommander.class")));
			
			System.err.println("Copying file: " + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "SQLServerDatabaseCommander.class");
			copyInputStream(new FileInputStream("org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "SQLServerDatabaseCommander.class"), new BufferedOutputStream(new FileOutputStream(classFile.getPath() + File.separator + "SQLServerDatabaseCommander.class")));

			System.err.println("Copying file: " + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "DatabaseCommander.class");
	    	copyInputStream(new FileInputStream("org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "DatabaseCommander.class"), new BufferedOutputStream(new FileOutputStream(classFile.getPath() + File.separator + "DatabaseCommander.class")));

			System.err.println("Copying file: " + "org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "Logger.class");
			copyInputStream(new FileInputStream("org" + File.separator + "infoglue" + File.separator + "cmsinstaller" + File.separator + "Logger.class"), new BufferedOutputStream(new FileOutputStream(classFile.getPath() + File.separator + "Logger.class")));
			
			System.err.println("Copying file: " + "configTemplates" + File.separator + "Uninstall.bat");
	    	copyInputStream(new FileInputStream("configTemplates" + File.separator + "Uninstall.bat"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "Uninstall.bat")));
			//System.err.println("Copying file: " + "configTemplates" + File.separator + "Uninstall.lnk");
			//createShortcutFile(startMenuFolderPath);
			//copyInputStream(new FileInputStream("configTemplates" + File.separator + "Uninstall.lnk"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "Uninstall.lnk")));
			System.err.println("Copying file: " + "lib" + File.separator + "mysql-connector-java-3.0.6-stable-bin.jar");
	    	copyInputStream(new FileInputStream("lib" + File.separator + "mysql-connector-java-3.0.6-stable-bin.jar"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "mysql-connector-java-3.0.6-stable-bin.jar")));

			
			//copyInputStream(new FileInputStream("lib" + File.separator + "jtds-0.7.jar"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "jtds-0.7.jar")));
			/*
			copyInputStream(new FileInputStream("lib" + File.separator + "msutil.jar"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "msutil.jar")));
			copyInputStream(new FileInputStream("lib" + File.separator + "mssqlserver.jar"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "mssqlserver.jar")));
			copyInputStream(new FileInputStream("lib" + File.separator + "msbase.jar"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "msbase.jar")));
    		*/
    		/*
    		System.err.println("Copying file: " + "localConfigs/cms.properties");
	    	copyInputStream(new FileInputStream("localConfigs/cms.properties"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "cmsuninstall.properties")));
    		System.err.println("Copying file: " + "localConfigs/deliver.properties");
	    	copyInputStream(new FileInputStream("localConfigs/deliver.properties"), new BufferedOutputStream(new FileOutputStream(startMenuFolder + File.separator + "deliveruninstall.properties")));
			*/

			int i = 0;
			Properties p = new Properties();		
			Iterator iterator = removableDirectories.iterator();	
			while(iterator.hasNext())
			{
				String dir = (String)iterator.next();
				p.setProperty(i + ".removableDirectory", dir);
				i++;
			}
			
			p.setProperty("dbUrl", dbUrl);
			p.setProperty("databaseServer", databaseServer);
			p.setProperty("driverName", driverName);
			p.setProperty("tomcatHomePath", tomcatHomePath);
			p.setProperty("dbName", dbName);
			p.setProperty("hostName", hostName);
			
			p.store(new FileOutputStream(startMenuFolder + File.separator + "uninstall.properties"), "Uninstall information");			
		}
	}



	/**
	 * This method updates the config-files needed to deploy a new application with a context.
	 */
	public void updateTomcatConfiguration(String path) throws Exception
	{
		new File(path + File.separator + ".." + File.separator + "webapps" + File.separator + "infoglueCMS.xml").delete();
	}
	

	public void createShortcutFile(String programHome) throws Exception
	{
		FileInputStream fis = new FileInputStream("configTemplates/Uninstall.lnk");
		String result = "";
		StringBuffer sb = new StringBuffer();
		
		int c;
		while((c = fis.read()) != -1)
		{
			sb.append((char)c);
		}
		result = sb.toString();
		Logger.logInfo("result" + result);
		
		result = result.replaceAll("\\{path\\}", programHome);
		
		PrintWriter pw = new PrintWriter(new FileOutputStream("configTemplates/Uninstall.lnk"));
		pw.println(result);
		pw.close();
	}
	

	/**
	 * This is the method removes every trace of the application. 
	 */
	
	public void uninstall()
	{
		Logger.logInfo("Starting uninstall...");
		
		try
		{
			Logger.logInfo("Reading uninstall.properties...");
			Properties cmsProperties = new Properties();
			cmsProperties.load(new FileInputStream("uninstall.properties")); 
					
			int i = 0;
			String removableDirectory = cmsProperties.getProperty(i + ".removableDirectory");
			while(removableDirectory != null)
			{
				File currentRemovableDirectory = new File(removableDirectory);
				Logger.logInfo("Removing directory " + currentRemovableDirectory.getName());
				currentRemovableDirectory.delete();
				i++;
				removableDirectory = cmsProperties.getProperty(i + ".removableDirectory");
			}

			String url 		      = cmsProperties.getProperty("dbUrl");
			String databaseServer = cmsProperties.getProperty("databaseServer");
			String databasePort   = cmsProperties.getProperty("databasePort");
			String databaseInstance = cmsProperties.getProperty("databaseInstance");
			String driverName     = cmsProperties.getProperty("driverName");
			String dbName     	  = cmsProperties.getProperty("dbName");
			String dbSuffix       = cmsProperties.getProperty("dbSuffix");
			String hostName       = cmsProperties.getProperty("hostName");
			
			System.out.print("Do you want to delete the database and all associated data as well (This action will be irreversible). [Yes]:");
			if(getInputWithDefault("Yes").toLowerCase().indexOf("yes") > -1)
			{
				System.out.print("Please state the database administrator username:");
				String userName = getInputWithDefault("");
				System.out.print("Please state the database administrator password:");
				String password = getInputWithDefault("");
					
				MySQLDatabaseCommander commander = new MySQLDatabaseCommander(driverName, databaseServer, databasePort, databaseInstance, url, userName, password, "", "", dbName, dbSuffix, hostName, false, false, false, false, false, false);
				commander.deleteDatabase();
			}	
			
			updateTomcatConfiguration(cmsProperties.getProperty("tomcatHomePath"));
			
			String currentDir = System.getProperty("user.dir");
			new File(currentDir).deleteOnExit();
			
			System.exit(0);
		}
		catch(Exception e)
		{
			Logger.logInfo("Error:" + e.getMessage());
		}
	}
	
	
	/**
	 * Just copies the files...
	 */
	
	private void copyInputStream(InputStream in, OutputStream out) throws IOException
	{
	    byte[] buffer = new byte[1024];
    	int len;

    	while((len = in.read(buffer)) >= 0)
      		out.write(buffer, 0, len);

    	in.close();
    	out.close();
  	}
  	
  	
  	public String getInputWithDefault(String defaultValue) throws Exception
	{
		String value = "";
		
		// block until enter is pressed
		while (true) 
		{
	    	char c = (char)System.in.read();
	        if (c == '\r') 
	        {
	        	c = (char)System.in.read();
	            if (c == '\n') 
	            {
	               break;
	            } 
	            else 
	            {
	               continue;
	            }
	        } 
	        else if (c == '\n') 
	        {
	            break;
	        } 
	        else 
	        {
	            value += c;
	        }
		}
		
		if(value.equals(""))
			value = defaultValue;
		
		return value;
	}
}