import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.util.Vector;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;

class WinRegistry {
  public static final int HKEY_LOCAL_MACHINE = 0x80000002;
  public static final int REG_SUCCESS = 0;
  public static final int REG_NOTFOUND = 2;
  public static final int REG_ACCESSDENIED = 5;

  private static final int KEY_ALL_ACCESS = 0xf003f;
  private static final int KEY_READ = 0x20019;
  private static Preferences userRoot = Preferences.userRoot();
  private static Preferences systemRoot = Preferences.systemRoot();
  private static Class<? extends Preferences> userClass = userRoot.getClass();
  private static Method regOpenKey = null;
  private static Method regCloseKey = null;
  private static Method regQueryValueEx = null;
  private static Method regEnumValue = null;
  private static Method regQueryInfoKey = null;
  private static Method regEnumKeyEx = null;
  private static Method regCreateKeyEx = null;
  private static Method regSetValueEx = null;
  private static Method regDeleteKey = null;
  private static Method regDeleteValue = null;

  static {
    try {
      regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
          new Class[] { int.class, byte[].class, int.class });
      regOpenKey.setAccessible(true);
      regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
          new Class[] { int.class });
      regCloseKey.setAccessible(true);
      regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
          new Class[] { int.class, byte[].class });
      regQueryValueEx.setAccessible(true);
      regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
          new Class[] { int.class, int.class, int.class });
      regEnumValue.setAccessible(true);
      regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
          new Class[] { int.class });
      regQueryInfoKey.setAccessible(true);
      regEnumKeyEx = userClass.getDeclaredMethod(  
          "WindowsRegEnumKeyEx", new Class[] { int.class, int.class,  
              int.class });  
      regEnumKeyEx.setAccessible(true);
      regCreateKeyEx = userClass.getDeclaredMethod(  
          "WindowsRegCreateKeyEx", new Class[] { int.class,  
              byte[].class });  
      regCreateKeyEx.setAccessible(true);  
      regSetValueEx = userClass.getDeclaredMethod(  
          "WindowsRegSetValueEx", new Class[] { int.class,  
              byte[].class, byte[].class });  
      regSetValueEx.setAccessible(true); 
      regDeleteValue = userClass.getDeclaredMethod(  
          "WindowsRegDeleteValue", new Class[] { int.class,  
              byte[].class });  
      regDeleteValue.setAccessible(true); 
      regDeleteKey = userClass.getDeclaredMethod(  
          "WindowsRegDeleteKey", new Class[] { int.class,  
              byte[].class });  
      regDeleteKey.setAccessible(true); 
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  private WinRegistry() {  }

  /**
   * Read a value from key and value name
   * @param hkey   HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
   * @param key
   * @param valueName
   * @return the value
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static String readString(int hkey, String key, String valueName) 
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException 
  {
    if (hkey == HKEY_LOCAL_MACHINE) {
      return readString(systemRoot, hkey, key, valueName);
    }
	return null;
  }

  
  private static String readString(Preferences root, int hkey, String key, String value)
    throws IllegalArgumentException, IllegalAccessException,
    InvocationTargetException 
  {
    int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
        new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
    if (handles[1] != REG_SUCCESS) {
      return null; 
    }
    byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
        new Integer(handles[0]), toCstr(value) });
    regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
    return (valb != null ? new String(valb).trim() : null);
  }
  

  
  private static byte[] toCstr(String str) {
    byte[] result = new byte[str.length() + 1];

    for (int i = 0; i < str.length(); i++) {
      result[i] = (byte) str.charAt(i);
    }
    result[str.length()] = 0;
    return result;
  }
}

public class TCInstallerMain {

	/**
	 * @param args
	 */
	
	static final String m_strCfgFile = new String("oraconfig.cfg");
	static TCAgentOraConfig m_agentConfig = new TCAgentOraConfig();
	static TCLogHandler m_LogHandler = new TCLogHandler();
	static String m_ScriptName;
	static String m_OSpckg;
	
	public static void main(String[] args) 
	{	
		String sJavaVer = System.getProperty("java.version");
		System.out.println("Detected java version: "+sJavaVer);
		
		if (sJavaVer.compareTo("1.6")<0)
		{
			System.out.println("Oracle agent requires at least Java 1.6");
			try {
				System.in.read();
			} finally {
				return;
			}
		}
		
		m_LogHandler.Init("Install.log");					        
		TCAgentOraConfigServices OraCfgsvcs = new TCAgentOraConfigServices();
		OraCfgsvcs.init(m_strCfgFile);
		try {
			long hResult = OraCfgsvcs.read(m_agentConfig);
			if (hResult!=0)
			{
				m_LogHandler.CreateLogEntry("Main",0,"Unable to read configuration file");
				return;
			}
		}
		catch (Exception e) {
			e.printStackTrace();			
			try {
				m_LogHandler.CreateLogEntry(e,0);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
				
		if (args.length>2)
		{
			String strcmd = args[0].toUpperCase();
			m_OSpckg = args[1].substring(1);
			m_ScriptName = args[2].substring(1);
			if (strcmd.compareTo("-INSTALL")==0)
			{    			
				Install(m_OSpckg,m_ScriptName);
			}
			else if (strcmd.compareTo("-UNINSTALL")==0)
			{
				try {
					Uninstall();
				} catch (Exception e) {
					e.printStackTrace();
					try {
						m_LogHandler.CreateLogEntry(e,0);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} 
			}
		}
		else {
			System.out.println("Usage: TCOraInstaller -[INSTALL/UNINSTALL] -[OSPCKG] -[SCRIPT]");
			try {
				System.in.read();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	static void Uninstall() throws IOException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalStateException, IllegalBlockSizeException, 
		BadPaddingException, TCUnexpectedException, 
		TCBufferTooSmallException, TCNullParameterException, TCInvalidPacketException, 
		InterruptedException
	{
		String strOEMname = "/******************************************************************\n"+
		"************ TaskCentre Oracle Agent Uninstaller ******************\n"+
		"/******************************************************************\n";
        TCClientConnectorServices clientServices;
            
		//try 
        {
        	byte []consoleinput = new byte[300];

		clientServices = null;

        	SYSTASKPARAMS taskParamsOut = null; 
        	
	         try {
	        	clientServices = new TCClientConnectorServices(m_agentConfig,false);
	                taskParamsOut = clientServices.DoSysTask(TCDOSYSTASKCODE.SYSTASK_GETOEMINFO, new SYSTASKPARAMS());                                              
	         } catch (Exception e) {
	         }
	
	         if (taskParamsOut != null)
	         {
	         	strOEMname = 
	         		strOEMname.replaceAll("TaskCentre Oracle Agent",SYSTASKPARAMS.byteArray2String(taskParamsOut.Param6));
			 }
	         TCSynchronizedOutput.display(strOEMname);		        	
        	
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Reading configuration file...");
			TCSynchronizedOutput.display("Reading configuration file...");
			TCInstallFilesServices InstallFilesvcs = new TCInstallFilesServices();
			InstallFilesvcs.Init(m_agentConfig.m_agentFolder,"TCOracleAgent.jar");
			
			long hResult =0;
			// Unregister agent
			/*
			Automatic unregistration disabled for now - see #88286
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Performing agent unregistration...");
			TCSynchronizedOutput.display("Performing agent unregistration...");			
	        long hResult = clientServices.UnregisterAgent(m_agentConfig.m_eidAgent);
			
	        if(hResult != 0)
	        {
	        	if (hResult!=-9222243916449841152l)
	        	{
	    			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Agent Unregistration failure hResult = "+hResult);
	    			TCSynchronizedOutput.display("Agent Unregistration failure hResult = "+hResult);	        		
	        	}
	        	else
	        	{
	    			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Agent not registered");
	    			TCSynchronizedOutput.display("Agent not registered");	        			        		
	        	}
	        }
	        else {
	        	m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Agent unregistered successfully.");
	        	TCSynchronizedOutput.display("Agent unregistered successfully.");
	        }
	        */

	        //	Let's try to uninstall service
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Uninstalling...");
			TCSynchronizedOutput.display("Uninstalling...");		        
	        File dir = new File(m_agentConfig.m_agentFolder);
	        String command = "";

	        // NOTE: Uninstall script has the same name as Install one but with "Un" prefix
	        if (new File(dir+"/bin/"+"Un"+m_ScriptName).isFile()==true)
	        	command = dir+"/bin/"+"Un"+m_ScriptName;
	        else if (new File(dir+"/bin/"+m_ScriptName).isFile()==true)
        		command = dir+"/bin/"+m_ScriptName+" stop";
	        
        	if (command.length()>1)
        	{
				Process p = Runtime.getRuntime().exec(command);
				p.waitFor();
        	}	    
        	else
        	{
    			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Unable to locate uninstall script");
    			TCSynchronizedOutput.display("Unable to locate uninstall script");	        		        	
    		}
			
	        //Remove triggers
	        try
	        {
		        m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Removing installed triggers...");
		        System.out.println("Removing installed triggers...");	        	
		        InstallFilesvcs.CopyFile(m_agentConfig.m_agentFolder+"/bin/oratriggers.dat","oratriggers.dat");
		        
		        TCOraTriggersFileServices oraTriggersHelper = new TCOraTriggersFileServices();
	            hResult = oraTriggersHelper.getTriggers();
	            if(hResult != 0)
	                        throw new Exception("Unable to enumerate triggers");
	            
	            Vector m_oraTriggers = oraTriggersHelper.m_vecTriggers;
	            DropTriggers(m_oraTriggers);
            	new File("oratriggers.dat").delete();
            }
            catch (FileNotFoundException e){
		        m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"No triggers located");
		        System.out.println("No triggers located");
            }
            catch (Exception e)
            {
            	e.printStackTrace();
            	m_LogHandler.CreateLogEntry(e,2);
            }
            
	        m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Removing files...");
	        System.out.println("Removing files");			
			//Remove files
	        String strNotRemoved = InstallFilesvcs.Remove();
	        if (strNotRemoved.length()>1)
	        {
	        	System.out.println("Failed to remove following files and folders: "+strNotRemoved);
	        	m_LogHandler.CreateLogEntry("TCInstallerMain.Uninstall",0,"Failed to remove following files and folders: "+strNotRemoved);
	        	
	        	System.out.println("Would you like to retry?");
	        	String response;
				do
				{
					System.in.read(consoleinput);			
					response = Byte2String(consoleinput);
					response = response.toUpperCase();
					strNotRemoved = InstallFilesvcs.Remove();
					if (strNotRemoved.length()<2) break;
					else {
			        	System.out.println("Failed to remove following files and folders: "+strNotRemoved);
			        	m_LogHandler.CreateLogEntry("TCInstallerMain.Uninstall",0,"Failed to remove following files and folders: "+strNotRemoved);						
					}
				}while (response.compareTo("Y")==0);
	        }
	        
	        //remove Linux autostart stuff
	        try{
	        	new File("/etc/rc.d/init.d/TCOraAgent").delete();
	        	new File("/etc/rc.d/rc2.d/S99TCOraAgent").delete();
	        	new File("/etc/rc.d/rc3.d/S99TCOraAgent").delete();
	        	new File("/etc/rc.d/rc5.d/S99TCOraAgent").delete();
	        }
	        catch (Exception e)
	        {
	        	//nothing happened - OS don't have autostart scripts
	        }
		}  
		try {
			TCSynchronizedOutput.display("Agent removed from system");				
			m_LogHandler.CreateLogEntry("Uninstall",2,"Agent removed from system");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	        
	}
	
	private static void DropTriggers(Vector _oraTriggers)
	{
		long hResult = 0;
	
		try
		{
			for(int i=0;i<_oraTriggers.size();i++)
			{
				TCORAFILETRIGGERS trigger = (TCORAFILETRIGGERS) _oraTriggers.get(i);
				
					TCJDBCServices jdbc = new TCJDBCServices();
					
					hResult = jdbc.init(trigger.HOST, trigger.PORT , trigger.SID, trigger.USER, trigger.PASS, trigger.CONNECTAS);
					if(hResult != 0)
						throw new Exception("jdbc init failed with "+hResult);
					//X9_TV_27_9F9BEA44_2423_4
					TCSynchronizedOutput.display("Removing trigger '"+trigger.USER+"."+trigger.TRIGGER+"'");
					hResult = jdbc.dropTrigger(trigger.USER+"."+trigger.TRIGGER);
					if(hResult != 0)
						m_LogHandler.CreateLogEntry("DropTriggers",0,"Droptrigger failed with hResult " + hResult);
						
					jdbc.dropTrigger("TCAGENTAPI450");
					
					hResult = jdbc.commit();
					if(hResult != 0)
						m_LogHandler.CreateLogEntry("DropTriggers",0,"Commit failed with hResult " + hResult);
			}	
		}
		catch (Exception e)
		{
			e.printStackTrace();
			try {
				m_LogHandler.CreateLogEntry(e,0);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}



	

 public static String removeChar(String s, char c)
    {
      String r = "";
      for (int i=0; i< s.length() ; i++)
      {
        if(s.charAt(i) != c) r+=s.charAt(i);
        }
       return r;
    }


    static boolean isAgentRegistered(TCClientConnectorServices clientServices) throws TCInvalidParameterException,  TCNullParameterException, TCUnexpectedException, TCBufferTooSmallException, java.net.UnknownHostException, java.security.InvalidKeyException,  javax.crypto.NoSuchPaddingException, java.security.InvalidAlgorithmParameterException, java.security.NoSuchAlgorithmException,  javax.crypto.IllegalBlockSizeException,  javax.crypto.BadPaddingException,  java.io.IOException,  TCInvalidPacketException
    {
        TCSTOREENTRY[] storeEntries;
        java.net.InetAddress i = java.net.InetAddress.getLocalHost();
                    
        // open all event providers
        storeEntries = clientServices.OpenMultipleEntriesByGUID( TCSTORETYPE.STYP_CONFIG, new TCGUID("{FCDE15AC-F8AD-4925-98040C781571232C}", ""));
          		 
		String strCurrentAgent = new String(TCGUIDENTRYTYPE.ETGUID_TCORAAGENT_GUID_CONFIG+"+" +i.getHostName());
		 
		strCurrentAgent= removeChar(strCurrentAgent, '{');
		strCurrentAgent = removeChar(strCurrentAgent, '}');
		strCurrentAgent = removeChar(strCurrentAgent, '-');
		    	 	  
		for(int ii=0;ii<storeEntries.length;ii++)
		{					
			TCData data1 = storeEntries[ii].getData();
			String strComp = null; 
							
			try{
				strComp = data1.getTextChunk(new String("LKP1"));	
							
				if(strCurrentAgent.compareTo( removeChar(strComp,'-') ) == 0) 
				{				
		 	       return true;		 	    
				}
		 			   
			}
			catch(Exception e)
			{
				// ignore if chunk not found
				continue;
			}											
		}   
		
		return false;    
    }




	static void Install(String OSpckg, String OSscript)
	{
		long hResult;
		String strInstance="ORAAGENT";
		String strOEMname =
			"************************************************************\n"+
			"************ TaskCentre Oracle Agent Installer *************\n"+
			"************************************************************";
		String strOEMServiceName = "";
		TCAgentOraConfigServices OraCfgsvcs = new TCAgentOraConfigServices();
		OraCfgsvcs.init(m_strCfgFile);
		try 
		{                   
			byte[] consoleinput = new byte[300]; 
			TCIWENTRYID eidAccount;
            SYSTASKPARAMS taskParamsOut = null; 
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Installer started...");			
			
			System.out.println("\nPlease enter TaskCentre server address: (default: localhost)");	
			System.in.read(consoleinput);	
			m_agentConfig.m_tcServer = Byte2String(consoleinput);			
			if (m_agentConfig.m_tcServer.compareTo("")==0) m_agentConfig.m_tcServer = "localhost";
			
			System.out.println("Please enter TaskCentre server port (default: 4222):");
			System.in.read(consoleinput);
			String port = Byte2String(consoleinput);
			try
			{m_agentConfig.m_tcPort = Integer.parseInt(port);}
			catch (Exception e) {
				m_agentConfig.m_tcPort = 4222;
			}
			
			TCClientConnectorServices clientServices = new TCClientConnectorServices(m_agentConfig,false);
			
            try {
	                taskParamsOut = clientServices.DoSysTask(TCDOSYSTASKCODE.SYSTASK_GETOEMINFO, new SYSTASKPARAMS());                                              
	         } catch (Exception e) {
	         }
	
	         if (taskParamsOut != null)
	         {
				 strOEMServiceName = SYSTASKPARAMS.byteArray2String(taskParamsOut.Param6);

	         	strOEMname =
					strOEMname.replaceAll("TaskCentre Oracle Agent", strOEMServiceName);
				}
	         TCSynchronizedOutput.display(strOEMname);			
			
			System.out.println("\nPlease enter administrator account name: (default: Administrator)");	
			System.in.read(consoleinput);				
			String stradminaccount = Byte2String(consoleinput);			
			if (stradminaccount.compareTo("")==0) stradminaccount = "Administrator";
			
			System.out.println("\nPlease enter administrator account password:");	
			System.in.read(consoleinput);				
			String stradminpwd = Byte2String(consoleinput);	
			
			
			//clientServices.LogonNamed(stradminaccount,stradminpwd);
			eidAccount = clientServices.LogonNamedEx(stradminaccount,stradminpwd);
			if (eidAccount==null)
				throw new Exception("Logon failed("+clientServices.m_hResult+")");			



			
	        /*********************** Files installation  ***********************/
			//Scanner sc = new Scanner(System.in);
		
			System.out.println("Please enter destination directory:");				
			//m_agentConfig.m_agentFolder = sc.nextLine();
			System.in.read(consoleinput);			
			m_agentConfig.m_agentFolder = Byte2String(consoleinput);
			File destdir = new File(m_agentConfig.m_agentFolder);
			
			TCInstallFilesServices InstallFilesvcs = new TCInstallFilesServices();
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Copying files to:"+m_agentConfig.m_agentFolder);
			InstallFilesvcs.Init(m_agentConfig.m_agentFolder, OSpckg, strOEMServiceName);			
			
			if (InstallFilesvcs.AgentDirExists()==false)
			{
				String response;
				System.out.println("Specified directory doesn't exist. Do you want to create it (Y/N)?");
				System.in.read(consoleinput);	
				response = Byte2String(consoleinput);
				response = response.toUpperCase();
				//if (response.length()>1)
				{
					if (response.charAt(0)=='Y')
					{
							m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Creating "+m_agentConfig.m_agentFolder);
							destdir.mkdirs();
					}
					else return;
				}		
			}
			m_agentConfig.m_agentFolder += "/TCOracleAgent";
			InstallFilesvcs.Copy();
			InstallFilesvcs.CopyFile("classes.jar",m_agentConfig.m_agentFolder+"/bin/classes.jar");
			InstallFilesvcs.CopyFile("classes12.zip",m_agentConfig.m_agentFolder+"/bin/classes12.zip");
			
			//Try to modify file attributes to allow execution
			try
			{
				Process p = Runtime.getRuntime().exec("chmod +x "+m_agentConfig.m_agentFolder+
						"/bin/wrapper");
				p.waitFor();
				p = Runtime.getRuntime().exec("chmod +x "+m_agentConfig.m_agentFolder+
					"/bin/TCOraAgent");					
			}
			catch (Exception e){};
			
			
			m_agentConfig.m_agentFolder = destdir.getAbsolutePath()+"/TCOracleAgent";
			
			System.out.println("\nPlease enter Oracle agent instance name: (default: ORAAGENT)");				
			System.in.read(consoleinput);	
			strInstance = Byte2String(consoleinput);			
			if (strInstance.compareTo("")==0) strInstance = "ORAAGENT";			
				
			
			/*********************** TC Registration  ***********************/
			TCData data = new TCData();
	        TCIWENTRYID eidRoot = new TCIWENTRYID();
	        TCIWENTRYID eidEntry = new TCIWENTRYID();
	        TCIWENTRYID eidAPDEntry = new TCIWENTRYID();
	        
            java.net.InetAddress i = java.net.InetAddress.getLocalHost();
            
            hResult = clientServices.RegisterAgent( TCGUIDENTRYTYPE.ETGUID_TCORAAGENT_GUID_CONFIG, i.getHostName(), strInstance, eidEntry);
            if(hResult != 0)
                  throw new Exception("Agent Registration failure hResult = "+hResult);
            
            TCRegisterAgentReplyPacket registerAgentRPacket  = (TCRegisterAgentReplyPacket) clientServices.m_lastReceivedPacket;
            
            // find APDRoot for the Oracle trigger
            TCSTOREENTRY storeEntry = new TCSTOREENTRY();
            long hCTX = 0;
            hCTX = clientServices.FindFirstByParentCTX(TCSTORETYPE.STYP_CONFIG, eidRoot, TCENTRYTYPE.ET_APDROOT,TCGUIDENTRYTYPE.ETGUID_TCORAAGENT_GUID_GLOBAL , storeEntry);
            if(clientServices.m_hResult != 0)
            	throw new Exception("Agent Registration failure hResult = "+hResult);   
            clientServices.CloseCTXHandle(TCSTORETYPE.STYP_CONFIG, hCTX);
            
            hResult = clientServices.CreateEntry(TCSTORETYPE.STYP_CONFIG, TCENTRYTYPE.ET_ACTIONPROVDATA, TCGUIDENTRYTYPE.ETGUID_TCORAAGENT_GUID_GLOBAL, eidAPDEntry);
            if(hResult != 0)
            {
            	throw new Exception("Agent Registration failure hResult = "+hResult);                     
            }
            data.AddChunk(TChunks.ORATRIGCT_COMP, i.getHostName());                       
            data.AddChunk(TChunks.ORATRIGCT_INST, strInstance);
            data.AddChunk(TChunks.ORATRIGCT_AEID,eidEntry.getBytes());
            data.AddChunk(TChunks.ORATRIGCT_POLI, m_agentConfig.m_pollingInterval);
            
            hResult = clientServices.SaveEntry(TCSTORETYPE.STYP_CONFIG, eidAPDEntry, storeEntry.getEntryID(), 0, data);
            if(hResult != 0)
            {
            	throw new Exception("Agent Registration failure hResult = "+hResult);                       
            }
            m_agentConfig.m_eidAgent = eidEntry;
            m_agentConfig.m_agentPass  = registerAgentRPacket.getPasswordStr();
            m_agentConfig.m_agentName= registerAgentRPacket.getUsernameStr();

			//ok - prevent nulls for master/slave before write
			if (m_agentConfig.m_SlaveSvr == null) m_agentConfig.m_SlaveSvr = m_agentConfig.m_tcServer;
			m_agentConfig.m_MasterSvr = m_agentConfig.m_tcServer;
			
            hResult = OraCfgsvcs.write(m_agentConfig);
            if(hResult != 0)
            	throw new Exception("Failed to save agent configuration: hResult = "+hResult);         
            
            
			m_LogHandler.CreateLogEntry(TCInstallerMain.class.toString(),2,"Running installation script");

			if(OSpckg.indexOf("Windows") != -1)
			{
			    updateWrapperConf(m_agentConfig.m_agentFolder);			    
		    }
				
	        InstallFilesvcs.CopyFile(m_strCfgFile,m_agentConfig.m_agentFolder+"/bin/"+m_strCfgFile);
	        
	        String command = m_agentConfig.m_agentFolder+"/bin/"+OSscript;       
		System.out.println("Running "+command);	
	        Process p = Runtime.getRuntime().exec(command);
		        p.waitFor();
			if (p.exitValue()!=0) 
			{
				command +=" start";
		        	Process p1 = Runtime.getRuntime().exec(command);
		       		p1.waitFor();
				m_LogHandler.CreateLogEntry("Install",2,"Install script(cmd) returned "+p1.exitValue());
				TCSynchronizedOutput.display("Install script returned "+p1.exitValue());
			}
			else
			{
				m_LogHandler.CreateLogEntry("Install",2,"Install script returned "+p.exitValue());
				TCSynchronizedOutput.display("Install script returned "+p.exitValue());
			}            
            			
			
			try
			{
				int readed=0,offset=0;
				char []szContents = new char[50000];
				String strcontents = new String();				
				String etcpath = new String("/etc/init.d/TCOraAgent");
				String scriptpath = m_agentConfig.m_agentFolder+"/bin/TCOraAgent";
				
				InstallFilesvcs.CopyFile(scriptpath,etcpath);
				BufferedReader br = new BufferedReader(new FileReader(scriptpath));
				
				do 
				{
					readed = br.read(szContents,0,szContents.length);
					if (readed>0) strcontents += String.copyValueOf(szContents,0,readed);
					offset += readed;
				}while (readed>=0);

				strcontents = strcontents.replaceAll("WRAPPER_CMD=\"./wrapper\"","WRAPPER_CMD=\""+m_agentConfig.m_agentFolder+"/bin/wrapper\"");
				strcontents = strcontents.replaceAll("WRAPPER_CONF=\"../conf/wrapper.conf\"",
						"WRAPPER_CONF=\""+m_agentConfig.m_agentFolder+"/conf/wrapper.conf\"");
				br.close();
				
				BufferedWriter bw = new BufferedWriter(new FileWriter(etcpath));
				bw.write(strcontents);
				bw.flush();
			}
			catch(Exception e)
			{
			}
						
			
			TCSynchronizedOutput.display("Agent registration successfull.");			
		}
		catch (Exception e)
		{
			e.printStackTrace();			
			try {
				m_LogHandler.CreateLogEntry(e,0);
				Uninstall();
			} 
			catch (Exception e2) {
				e2.printStackTrace();
			}
			System.exit(50);			
		}
		
		
		try {
			TCSynchronizedOutput.display("Installation finished");				
			m_LogHandler.CreateLogEntry("Install",2,"Installation finished");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static final String readJRE()
	{
	   String key;	   
	   String retVal = "java";	     
       try
		{
		   key = "SOFTWARE\\Wow6432Node\\JavaSoft\\Java Runtime Environment\\";
	       String current = WinRegistry.readString (WinRegistry.HKEY_LOCAL_MACHINE, key, "CurrentVersion");
		   if(current == null)
		   {
			 key = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
			 current = WinRegistry.readString (WinRegistry.HKEY_LOCAL_MACHINE, key, "CurrentVersion");
		   }

		   key+= current;
	       String _retVal = WinRegistry.readString (WinRegistry.HKEY_LOCAL_MACHINE, key, "JavaHome");
		   if(_retVal != null)
		   {
		     _retVal+= "\\bin\\java";		    
		      retVal = _retVal;
		   }
	    }
	    catch(Exception e) {}
	
	   return retVal;
	}

	public static final int updateWrapperConf(String agentFolder)
	{
		System.out.println(agentFolder);

		try{
		 File file = new File(agentFolder+"\\conf\\wrapper.conf");
         BufferedReader reader = new BufferedReader(new FileReader(file));
         String line = "", oldtext = "";
         while((line = reader.readLine()) != null)
         {
                 oldtext += line + "\r\n";
         }
         reader.close();
			 
		 String jreLoc = readJRE();
		 jreLoc = jreLoc.replaceAll("\\\\","\\\\\\\\");
         String newtext = oldtext.replaceFirst("wrapper.java.command=java","wrapper.java.command="+jreLoc);
			            
         FileWriter writer = new FileWriter(agentFolder+"\\conf\\wrapper.conf");
             writer.write(newtext);writer.close();
         }
         catch (IOException ioe)
             {
             ioe.printStackTrace();
         }
		 return 0;		
	}


	public static final String Byte2String(byte[] buf)
	{
	      StringBuffer sb = new StringBuffer();
		String resstr;

	      for (int j=0; j<buf.length-2; j++) 
	      {
	    	  if ((char)(buf[j])=='\r' || (char)(buf[j])=='\n')
	    		  break;
	            sb.append((char)(buf[j]));          
	      }
	            
	      resstr = sb.toString();   
	      return resstr;
	}	
}



