<%
/**
 *	Processing page for (specfic types) EgNewServer.jsp
 *	Specific types are MSExchangeOnline, Microsoft_Sharepoint_Online, MS_Office_365, MS_Skype_Online, Microsoft_Teams and Microsoft OneDrive for Business.
 *
 *	@author		Meena.V
 *	@created	20/07/2018 - MSExchangeOnline, Microsoft_Sharepoint_Online and MS_Office_365
 *	@modified	15/11/2018 - MS_Skype_Online
 *  @modified	06/06/2019 - Microsoft_Teams
 *  @modified	26/06/2019 - MS_OneDrive_Business
 */
%>

<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import = "com.egurkha.admin.ComponentAdd"%>
<%@ page import = "com.egurkha.admin.ComponentModify" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.admin.UserAssociateComponent"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "net.sf.json.JSONObject"%>
<%@ page import = "net.sf.json.JSONArray"%>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
%>

<%
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	String selectedServerGroup = request.getParameter("selectedServerGroup");
	if (selectedServerGroup == null)
	{
		selectedServerGroup = "-1";
	}
	String stype = request.getParameter("stype");
	//String treeViewSrc = request.getParameter("treeViewSrc");
	String fromWizard = request.getParameter("fromWizard");
	String mserver = request.getParameter("modifyserver");
	rootJSON.put("selectedServerGroup",selectedServerGroup);
	rootJSON.put("selectedServer",stype);

	boolean modifying = (mserver != null && mserver.equalsIgnoreCase("true"));
	String hostip = request.getParameter("hostip");
	String hostname = "";
	String sportno = request.getParameter("sportno");
	if (sportno == null)
	{
		sportno = "NULL";
	}
	String hportno = request.getParameter("hportno");
	if(mserver == null || !mserver.equals("true"))
	{
		hportno = sportno;
	}
	String oldhostname = request.getParameter("oldhostname");

	String fromResultPage = request.getParameter("fromResultPage");
	if(!StringUtils.isNull(fromResultPage) && fromResultPage.equals("true"))
	{
		oldhostname = "";
	}
	String remoteAgent = "";
	String remoteUser = request.getParameter("aluser");
	String remotepwd = request.getParameter("alpwd");
	String remotemode = request.getParameter("almode");
	String remotealos = request.getParameter("alos");
	String sshPort = request.getParameter("sshPort");
	String remoteType = request.getParameter("enableRemoteAgent");
	String remoteEncrypt = request.getParameter("alencrypt");
	String remoteKeyFile = request.getParameter("alkeyfile");
	String server_type = request.getParameter("servertype");
	String server_name = request.getParameter("servername");

	if(stype != null && stype != "")
	{
		remoteAgent = request.getParameter("remoteAgent");
		hostname = request.getParameter("hostname");
		String hostnameSuffix = request.getParameter("hostnameSuffix");
		hostname = (hostnameSuffix != null && hostnameSuffix.length()>0) ? (hostname + hostnameSuffix) : hostname;
	}
	IniFile externalIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
	String[] nickAloneTypes = externalIni.getVariables("NickName_Alone_Servers");
	List nickAloneTypesList = (nickAloneTypes != null) ? Arrays.asList(nickAloneTypes) : new ArrayList();
	boolean hideHostIPField = (nickAloneTypesList.contains(stype));
	if (hideHostIPField)
	{
		hostip = hostname;
	}
	rootJSON.put("host_IP",hostip);
	rootJSON.put("host_Name",hostname);

	String isPassive = request.getParameter("isPassive");
	if(isPassive == null)
	{
		isPassive = "false";
	}
	else
	{
		isPassive = isPassive.toLowerCase();
	}
		
	if (isPassive.equalsIgnoreCase("yes") || isPassive.equalsIgnoreCase("true"))
	{
		isPassive = "true";
	}
	else
	{
		isPassive = "false";
	}

	String enableRmtAgent = request.getParameter("enableRemoteAgent");
	String olderOSName = request.getParameter("olderosname");
	String olderModeName = request.getParameter("oldermodename");
	String olderSshPort = request.getParameter("$_sshPort");
	String preUser = request.getParameter("$_aluser");
	String tempIntAgentMode = request.getParameter("intAgentMode");
	String previousIntAgentMode = request.getParameter("previousintagentmode");
	String oldIntAgent = (String)session.getAttribute("int_agent");
	String prevAgents = request.getParameter("previousIntAgent");

	String checkBoxValues = request.getParameter("checkBoxValues");
	String[] componentsArr = StringUtils.getTokens(checkBoxValues, ",");
	String prevExtAgents = request.getParameter("prevExtAgents");
	String extAgentStr = request.getParameter("extAgents");
	String selExtAgents = request.getParameter("extAgents");

	String intAgentMode = request.getParameter("intAgentMode");
	String currAgent = request.getParameter("currAgents");
	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	String prevRemAgent = externalInfo.getRemoteAgentForHost(hostname);
	if (StringUtils.isNull(intAgentMode))
	{
		intAgentMode = "auto";
	}

	String user_id = _user.getLoginID();
	EgMappingInfo mappingInfo = new EgMappingInfo(_user.getLanguage());
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	UserAssociateComponent uacObj = new UserAssociateComponent(user_id,_user.getUserIP(session.getId()),session.getId());
	EgUuidInfo uuidInfo = new EgUuidInfo();
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean autoCreateZoneForUser = EgUuidInfo.autoCreateZone();
	String userCompMap = EgConfigInfo.egMgrConfigDir + "eg_usercompmapping.ini";

	egurkha.ConfigTopology EgConfigTopo = new egurkha.ConfigTopology();
	EgConfigTopo.createFile("eg_services.ini");
	EgDiscInfo egDiscInfo = new EgDiscInfo("manager");
	EgServicesInfo servicesInfo = new EgServicesInfo("manager");
	boolean isAllowHostName = servicesInfo.isAllowHostNames();
	int compSize = Integer.parseInt(EgConfigTopo.getValues("MISC_ARGS","MaxManagedComponentsForDisc"));
	boolean hasLimitExceeded=false;
	Vector managedAllComps = egDiscInfo.getAllManagedComponents();
	if (managedAllComps != null && (managedAllComps.size() > compSize))
	{
		hasLimitExceeded = true;
	}

	//To get valid operating system for eg_external.ini
	ArrayList extIniEntries = new ArrayList();
	Hashtable operatingSystems = new Hashtable();
	IniFile extIniObj = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
	String variables[] = extIniObj.getVariables("Default_Operating_Systems");
	Vector values = extIniObj.getAllValues("Default_Operating_Systems");
	if(variables != null && variables.length>0)
	{
		for(int ind=0;ind<variables.length;ind++)
		{
			operatingSystems.put(variables[ind],values.get(ind));
		}
	}
	Vector valuesSpecific = extIniObj.getAllValues("Specific_Operating_Systems");
	if(valuesSpecific != null && valuesSpecific.size()>0)
	{
		for(int ind=0;ind<valuesSpecific.size();ind++)
		{
			String valueStr = (String) valuesSpecific.get(ind);
			valueStr = valueStr.toLowerCase();
			operatingSystems.put(valueStr.substring(0,valueStr.indexOf(":")),valueStr.substring(valueStr.indexOf(":")+1));
		}
	}
	operatingSystems.put("other","Other");

	/* code for auditlog starts */
	AuditLogThread auditLogThread = new AuditLogThread();
	auditLogThread.setValue("Category","Admin");
	auditLogThread.setValue("User_id",_user.getLoginID());
	auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
	auditLogThread.setValue("Session_id",session.getId());
	auditLogThread.setValue("Module","Components");
	/* code for auditlog ends */
	
	//Expected error codes returned from ComponentAdd and ComponentModify class files
	String[] errCodes = new String[]{"eG_CLI_0032","eG_CLI_0033","eG_CLI_0034","eG_CLI_0035","eG_CLI_0036","eG_CLI_0037","eG_CLI_0038","eG_CLI_Err_0336","eG_CLI_Err_0337","eG_CLI_Err_0338","eG_CLI_Err_0339","eG_CLI_Err_0344","eG_CLI_Err_0345","eG_CLI_Err_0346","eG_CLI_Err_0347"};
	ArrayList errCodeList = new ArrayList(Arrays.asList(errCodes));

	//Initialising the service bean and stopping discovery
	//To ensure integrity
	//The following line is to ensure that the stopDiscovery & startDiscovery runs inside a sync block
	egurkha.ServiceBean servicer = new egurkha.ServiceBean();
	IniFile infraIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_infrastructure.ini");
	servicer.stopDiscovery();

	EgExternalInfo extInfo = new EgExternalInfo("manager");
	ComponentAdd compAdd;
	ComponentModify compModify;
	Hashtable compDetails = new Hashtable();
	Hashtable statusMap = new Hashtable();
	
	//Add/Modify components
	if (componentsArr != null)
	{
		int compArrLen = componentsArr.length;
		String hostnameOrigin = hostname;
		for (int m=0; m<compArrLen; m++)
		{
			compAdd = new ComponentAdd(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
			compModify = new ComponentModify(_user.getLoginID(),_user.getUserIP(session.getId()),session.getId());
			String tempHostName = hostname;
			int pos = tempHostName.lastIndexOf("_");
			hostname = (pos > -1) ? tempHostName.substring(0,pos) : tempHostName;
			pos = oldhostname.lastIndexOf("_");
			String _oldHName = (pos > -1) ? oldhostname.substring(0,pos) : oldhostname;

			IniFile mgrmiscIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
			String microsoftComponents[] = mgrmiscIni.getVariables("Microsoft_Components");
			Vector microsoftSuffixNameValues = mgrmiscIni.getAllValues("Microsoft_Components");
			int microsoftComponentsLength = microsoftComponents.length;
			for(int i=0;i<microsoftComponentsLength;i++)
			{
				String microsoftComponentkey = microsoftComponents[i];
				String microsoftSuffixVal = (String) microsoftSuffixNameValues.get(i);
				if (componentsArr[m].equalsIgnoreCase(microsoftSuffixVal))
				{
					stype = microsoftComponentkey;
					hostname += microsoftSuffixVal;
					hostip = (hideHostIPField) ? hostname : hostip;
					if (modifying)
					{
						_oldHName +=microsoftSuffixVal;
						hostip = (hideHostIPField) ? _oldHName : hostip;
					}
				}
			}
			compDetails = new Hashtable();
			compDetails.put("componenttype",stype);
			compDetails.put("hostip",hostip);
			compDetails.put("componentname",hostname);
			compDetails.put("port",sportno);
			prevRemAgent = externalInfo.getRemoteAgentForHost(hostname);
			if (modifying && (_oldHName != null && _oldHName.length()>0 && !_oldHName.equalsIgnoreCase(hostname)))
			{
				compDetails.put("oldcomponentname",_oldHName);
				compDetails.put("newcomponentname",hostname);
				prevRemAgent = externalInfo.getRemoteAgentForHost(_oldHName);
			}
			if (remoteType != null && (remoteType.equalsIgnoreCase("true") || remoteType.equalsIgnoreCase("yes")))
			{
				compDetails.put("agentless","yes");
				compDetails.put("mode",remotemode);
				if (remotealos != null && remotealos.length()>0)
				{
					String remoteOS = remotealos;
					if (operatingSystems.containsKey(remotealos))
					{
						remoteOS = operatingSystems.get(remotealos).toString();
					}
					compDetails.put("os",remoteOS);
				}
				compDetails.put("remoteagent",remoteAgent);
				if (remoteUser != null && remoteUser.length()>0)
				{
					compDetails.put("remoteuser",remoteUser);
				}
				if (remotepwd != null && remotepwd.length()>0)
				{
					compDetails.put("remotepwd",remotepwd);
				}
				if (sshPort != null && sshPort.length()>0)
				{
					compDetails.put("remoteport",sshPort);
				}
				if (remoteEncrypt != null && remoteEncrypt.length()>0)
				{
					compDetails.put("encrypttype",remoteEncrypt);
				}
				if (remoteKeyFile != null && remoteKeyFile.length()>0)
				{
					compDetails.put("keyfilename",remoteKeyFile);
				}
			}
			else
			{
				compDetails.put("agentless","no");
				compDetails.put("internalagentassignment",intAgentMode);
				compDetails.put("internalagent",currAgent);
			}
			String[] externalAgents = (modifying) ? extInfo.getExternalAgentsForHost(hostname) : extInfo.getExternalAgentsForHost(hostnameOrigin);
			if(externalAgents != null && externalAgents.length > 0)
			{
				String externalAgent = externalAgents[0];
				compDetails.put("externalagent",externalAgent);
			}
			else
			{
				String[] extAgent = request.getParameterValues("extAgents");
				if (extAgent != null && extAgent.length>1)
				{
					compDetails.put("externalagents",extAgent);
				}
				else
				{
					compDetails.put("externalagent",extAgentStr);
				}
			}
			if (isLimitedAdmin && user_id != null && user_id.length() > 0)
			{
				compDetails.put("CompUserMapping","yes");
				compDetails.put("uuiduser",user_id);
			}
			String statusStr = modifying ? compModify.modify(compDetails) : compAdd.add(compDetails);
			String tempElemStr = stype+"#"+hostname+":"+_oldHName;
			if (statusMap.containsKey(statusStr))
			{
				String tempPrevElemStr = statusMap.get(statusStr).toString().trim();
				tempElemStr = tempPrevElemStr + "|$|" + tempElemStr;
			}
			statusMap.put(statusStr,tempElemStr);
			/* code for user comp association starts */
			if (isLimitedAdmin && !modifying && statusStr.equalsIgnoreCase("eG_CLI_0030"))
			{
				Hashtable argsMap = new Hashtable();
				String resultStr = "";
				String compName = hostname + ":" + sportno;
				argsMap.put("userid",user_id);
				argsMap.put("componenttype",stype);
				argsMap.put("components",compName);
				argsMap.put("autoassociatetype","no");
				resultStr = uacObj.AssociateComponent(argsMap);

				//If autoCreateZoneForUser is set to true, then assign the component(s) to the user's zone.
				if (autoCreateZoneForUser && resultStr.length()>0 && resultStr.equalsIgnoreCase("eG_CLI_Res_0286"))
				{
					argsMap = new Hashtable();
					argsMap.put("userid",user_id);
					argsMap.put("stype",stype);
					argsMap.put("compname",compName);
					IniFile mgrMiscIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
					String associatedUsers = "";
					String associaedZones = "", disAssociatedZones = "";
					Hashtable resultMap = uacObj.AutoAssociateComponentToZone(argsMap);
					if (resultMap != null && !resultMap.isEmpty())
					{
						Enumeration enMapKeys = resultMap.keys();
						while (enMapKeys.hasMoreElements())
						{
							String userName = (String)enMapKeys.nextElement();
							String zoneName = mgrMiscIni.getValue("Auto_Created_Zone_User_Map",userName);
							if (zoneName == null || zoneName.trim().length() == 0)
							{
								zoneName = userName;
							}
							String resultStr2 = (String)resultMap.get(userName);
							if (!resultStr2.startsWith("eG_CLI_Err"))
							{
								associaedZones += zoneName + ",";
								associatedUsers += userName + ",";
							}
							else
							{
								disAssociatedZones += zoneName + ",";
							}
						}
					}
					String descMsg = "Zone "+ user_id +" could not be added and associated to the user "+user_id;
					AuditLogThread auditLogThread2 = new AuditLogThread();
					auditLogThread2.setValue("Category","Admin");
					auditLogThread2.setValue("User_id",_user.getLoginID());
					auditLogThread2.setValue("Host_ip",_user.getUserIP(session.getId()));
					auditLogThread2.setValue("Session_id",session.getId());
					auditLogThread2.setValue("Module","Zones");
					auditLogThread2.setValue("Activity","Auto Zone Configuration");
					if (associaedZones != null && associaedZones.length()>0)
					{
						associaedZones = associaedZones.substring(0,associaedZones.length()-1);
						associatedUsers = associatedUsers.substring(0,associatedUsers.length()-1);
						if (associaedZones.indexOf(",") > -1)
						{
							descMsg = "Zones "+ associaedZones +" have been added/modified and associated to the users "+associatedUsers+" successfully";
						}
						else
						{
							descMsg = "Zone "+ associaedZones +" has been added/modified and associated to the user "+associatedUsers+" successfully";
						}
					}
					if (disAssociatedZones != null && disAssociatedZones.length()>0)
					{
						disAssociatedZones = disAssociatedZones.substring(0,disAssociatedZones.length()-1);
						if (disAssociatedZones.indexOf(",") > -1)
						{
							descMsg += "Zones "+ disAssociatedZones +" have not been added/modified";
						}
						else
						{
							descMsg += "Zone "+ disAssociatedZones +" has not been added/modified";
						}
					}
					auditLogThread2.setValue("Description", descMsg);
					auditLogThread2.sendItToDB();
				}
			}
			/* code for user comp association ends */
		}
	}
	if (hasLimitExceeded)
	{
		servicer.startDiscovery("1");
	}
	else
	{
		servicer.startDiscovery("1",true);
	}
	EgConfigFilesSync.releaseInstance(infraIni);

	//To generate success or error alert messages
	if (statusMap != null)
	{
		int i=1;
		Enumeration e = statusMap.keys();
		String sucessMsg = "", tempErrMsg = "";
		String actionPerformed = modifying ? "modified" : "added";
		String msg = " "+_mapping.getTextDescription("admin.error.To upgrade your license")+", ";
		msg += _mapping.getTextDescription("admin.error.please contact")+" <b>license@eginnovations.com</b>";
		int statusMapSize = statusMap.size();
		rootJSON.put("resp_type_size",statusMapSize);
		while (e.hasMoreElements())
		{
			String statusStr = e.nextElement().toString().trim();//statusType
			String tempStr = statusMap.get(statusStr).toString().trim();//statusType
			String[] statusRes = StringUtils.getTokens(tempStr,"|$|");
			int statusResLen = statusRes.length;
			for (int k=0; k<statusResLen; k++)
			{
				String tempResStr = statusRes[k];
				String statusType = tempResStr.substring(0,tempResStr.indexOf("#"));
				String statusHostname = tempResStr.substring(tempResStr.indexOf("#")+1,tempResStr.indexOf(":"));
				String statusOldHostname = tempResStr.substring(tempResStr.indexOf(":")+1);
				statusType = mappingInfo.getComponentTypeDescription(statusType);

				//For error alert and its audit logs
				if (!statusStr.equalsIgnoreCase("eG_CLI_0030") && !statusStr.equalsIgnoreCase("eG_CLI_0047"))
				{
					/* code for auditlog starts */
					auditLogThread = new AuditLogThread();
					auditLogThread.setValue("Category","Admin");
					auditLogThread.setValue("User_id",_user.getLoginID());
					auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
					auditLogThread.setValue("Session_id",session.getId());
					auditLogThread.setValue("Module","Components");
					if(modifying)
					{
						auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " could not be modified properly");
						auditLogThread.setValue("Activity","Modify Component");
					}
					else
					{
						auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " could not be created properly");
						auditLogThread.setValue("Activity","Add Component");
					}
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
					Vector err_msg = new Vector();
					JSONObject obj = new JSONObject();
					String title = (modifying) ? _mapping.getTextDescription("admin.error.Modify component") : _mapping.getTextDescription("admin.error.Add new component");
					obj.put("Error_Title",title);
					//if(!StringUtils.isNull(treeViewSrc))
					//{
						//obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&treeViewSrc="+treeViewSrc+"&selectedServerGroup="+selectedServerGroup);
					//}
					//else
					//{
						//obj.put("Error_URL","EgDispServer.jsp?qctr=1&server="+stype+"&selectedServerGroup="+selectedServerGroup);
					//}

					String satusErr = mappingInfo.getErrorCodeValue(statusStr);
					if (satusErr.startsWith("Error :") || satusErr.startsWith("Error:"))
					{
						satusErr = satusErr.replace("Error",_mapping.getTextDescription("admin.auditlog.Reason"));
					}
					if (statusResLen == 1)
					{
						tempErrMsg = "The "+statusType+" ("+statusHostname+") component could not be "+actionPerformed+".<br/>";
					}
					else if (statusResLen > 1)
					{
						if (k == statusResLen-1)
						{
							tempErrMsg = (tempErrMsg.lastIndexOf(", ") == tempErrMsg.length()-2) ? tempErrMsg.substring(0,tempErrMsg.length()-2) : tempErrMsg;
							tempErrMsg += " and the "+statusType+" ("+statusHostname+") components could not be "+actionPerformed+".<br/>";
						}
						else
						{
							String tempStartStr = (tempErrMsg.length() == 0) ? "The " : "the ";
							tempErrMsg += tempStartStr+statusType+" ("+statusHostname+"), ";
						}
					}
					obj.put("Error_Msg_A_"+(i),tempErrMsg+"<br/>"+satusErr);
					if (errCodeList != null && errCodeList.contains(statusStr))
					{
						obj.put("Error_Msg_B_"+(i),"<br/>"+msg);
					}
					rootJSON.put("Error_Info_"+(i),obj);
				}
				else //For success alert and its audit logs
				{
					if (statusResLen == 1)
					{
						sucessMsg = "The "+statusType+" component ("+statusHostname+") has been "+actionPerformed+" successfully.";
					}
					else if(statusResLen > 1)
					{
						if (k == statusResLen-1)
						{
							sucessMsg = (sucessMsg.lastIndexOf(", ") == sucessMsg.length()-2) ? sucessMsg.substring(0,sucessMsg.length()-2) : sucessMsg;
							sucessMsg += " and the " +statusType+" ("+statusHostname+") components have been "+actionPerformed+" successfully.";
						}
						else
						{
							String tempStartStr = (sucessMsg.length() == 0) ? "The " : "the ";
							sucessMsg += tempStartStr+" "+statusType+" ("+statusHostname+"), ";
						}
					}
					rootJSON.put("Result_info",sucessMsg);
					/* code for auditlog starts */
					auditLogThread = new AuditLogThread();
					auditLogThread.setValue("Category","Admin");
					auditLogThread.setValue("User_id",_user.getLoginID());
					auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
					auditLogThread.setValue("Session_id",session.getId());
					auditLogThread.setValue("Module","Components");
					if(modifying)
					{
						auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " has been modified");
						auditLogThread.setValue("Activity","Modify Component");
					}
					else
					{
						auditLogThread.setValue("Description","Component "+statusHostname + " of type " +"$ctype$:"+statusType + " has been created");
						auditLogThread.setValue("Activity","Add Component");
					}
					//1. AUDITLOG - COMPONENT TYPE AND NICK NAME
					if(session.getAttribute("type").toString().equals("new"))
					{
						auditLogThread.setCurrentValue("01~~Component Type","$ctype$:"+statusType);
						auditLogThread.setCurrentValue("02~~Nick Name",statusHostname);
					}
					else
					{
						auditLogThread.setPreviousValue("02~~Nick Name",statusOldHostname);
						auditLogThread.setCurrentValue("02~~Nick Name",statusHostname);
					}

					//2. AUDITLOG - EXTERNAL AGENT
					String[] extAgent = request.getParameterValues("extAgents");
					EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
					String externalAgent = "";
					String managerHosts = specsInfo.getEGServer();
					boolean isMSPModel = EgUuidInfo.isMspModel();
					boolean isTypeHasExternalTests = specsInfo.isTypeHasExternalTests(stype);
					if (extAgent != null && extAgent.length > 0)
					{
						try
						{
							if (isTypeHasExternalTests)
							{
								externalAgent = StringUtils.getUniqueArrayAsString(extAgent);
							}
							else
							{
								if (isMSPModel)
								{
									EgUserElementsInfo usrElmntsInfo = new EgUserElementsInfo();
									ArrayList extAgnts = usrElmntsInfo.getExternalAgentsForUser(user_id);
									if (extAgnts == null || extAgnts.size() == 0)
									{
										externalAgent = managerHosts;
									}
									else
									{
										externalAgent = (String)extAgnts.get(0);
									}
								}
								else // Enterprise model
								{
									externalAgent = managerHosts;
								}
							}
							extIniEntries.add(new IniHelper(IniHelper.SET,"Test_Mapping_Section", statusHostname, externalAgent));
							if(modifying)
							{
								auditLogThread.setPreviousValue("External Agents",prevExtAgents);
							}
							auditLogThread.setCurrentValue("External Agents",externalAgent);
						}
						catch(Exception e1)
						{
							e1.printStackTrace();
						}
					}

					//3. AUDITLOG - AGENTLESS & ITS DETAILS
					if(modifying)
					{
						//Agentless
						if (prevRemAgent != null && prevRemAgent.trim().equals(""))
						{
							auditLogThread.setPreviousValue("Agentless","No");
						}

						//OS
						String oldOSName = "";
						if (olderOSName != null && olderOSName.length()>0)
						{
							oldOSName = (String)operatingSystems.get(olderOSName.trim().toLowerCase());
						}
						if(oldOSName !=null && !oldOSName.equalsIgnoreCase("null") && oldOSName.trim().length()>0)
						{
							auditLogThread.setPreviousValue("OS",oldOSName);
						}

						//Mode
						if(olderModeName !=null && !olderModeName.equalsIgnoreCase("null") && olderModeName.trim().length()>0)
						{
							auditLogThread.setPreviousValue("Mode",olderModeName.trim());
						}

						//Remote agent
						String olderRemoteAgentName = prevRemAgent;
						if(olderRemoteAgentName !=null && !olderRemoteAgentName.equalsIgnoreCase("null") && olderRemoteAgentName.trim().length()>0)
						{
							auditLogThread.setPreviousValue("Remote Agent",olderRemoteAgentName.trim());
						}
						else
						{
							auditLogThread.setPreviousValue("Remote Agent","-");
						}
					}
					else
					{
						if (enableRmtAgent != null && enableRmtAgent.equals("true"))
						{
							auditLogThread.setCurrentValue("Agentless","Yes");
						}
						else
						{
							auditLogThread.setCurrentValue("Agentless","No");
						}
					}
					if (remotealos != null && remotealos.length()>0)
					{
						String remoteOS = remotealos;
						if (operatingSystems.containsKey(remotealos))
						{
							remoteOS = operatingSystems.get(remotealos).toString();
						}
						auditLogThread.setCurrentValue("OS",remoteOS);
					}
					if (remotemode != null && remotemode.length()>0)
					{
						auditLogThread.setCurrentValue("Mode",remotemode);
					}
					if (remoteAgent != null && remoteAgent.length()>0)
					{
						auditLogThread.setCurrentValue("Remote Agent",remoteAgent);
					}

					//4. AUDITLOG - AGENTLESS USER DETAILS
					if(remotemode != null && !remotemode.equalsIgnoreCase("SNMP") && !remotemode.equalsIgnoreCase("Perfmon") && !remotemode.equalsIgnoreCase("other"))
					{
						if(!remoteUser.equals("NotApplicable"))
						{
							auditLogThread.setCurrentValue("User",remoteUser);
							if(modifying)
							{
								if(preUser !=null && !preUser.equalsIgnoreCase("null") && preUser.trim().length()>0)
								{
									auditLogThread.setPreviousValue("User",preUser.trim());
								}
							}
						}
					}

					//5. AUDITLOG - INTERNAL AGENT
					if (remoteType != null && (remoteType.equalsIgnoreCase("false") || remoteType.equalsIgnoreCase("no")))
					{
						if(tempIntAgentMode != null && !StringUtils.isNull(tempIntAgentMode))
						{
							auditLogThread.setCurrentValue("Internal Agent Assignment",intAgentMode);
						}
						if(modifying && (previousIntAgentMode !=null && previousIntAgentMode.length()>0))
						{
							auditLogThread.setPreviousValue("Internal Agent Assignment",previousIntAgentMode);
						}
					}
					//session.removeAttribute("int_agent");
					if(!StringUtils.isNull(oldIntAgent) || !StringUtils.isNull(currAgent)) 
					{
						if(currAgent == null)
							currAgent = statusHostname;
						else if(oldIntAgent == null)
							oldIntAgent = statusHostname;

						if(prevAgents != null && prevAgents.length()>0)
						{
							auditLogThread.setPreviousValue("Internal Agent",prevAgents);
						}
						auditLogThread.setCurrentValue("Internal Agent",currAgent);
					}
					auditLogThread.sendItToDB();
					/* code for auditlog ends */
				}
			}
			i++;
		}

		/* eg_external.ini entries starts */
		if (extIniEntries.size() > 0)
		{
			IniFile externalWrite = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + "eg_external.ini");
			for (int n=0; n<extIniEntries.size(); n++)
			{
				IniHelper iniHelper = (IniHelper)extIniEntries.get(n);
				String iniAction = iniHelper.getAction();
				String subject = iniHelper.getSubject();
				String key = iniHelper.getVariable();
				String value = iniHelper.getValue();
				if(iniAction != null)
				{
					if (iniAction.equals(IniHelper.SET))
					{
						externalWrite.setValue(subject,key,value);
					}
					else if (iniAction.equals(IniHelper.DELETE))
					{
						externalWrite.deleteValue(subject,key);
					}
				}
			}
			externalWrite.saveFile();
			EgConfigFilesSync.releaseInstance(externalWrite);
		}
		/* eg_external.ini entries ends */

		if (server_type == null)
		{
			server_type = request.getParameter("stype");
		}
		if (server_name == null)
		{
			server_name = hostname;
		}
		rootJSON.put("compType",server_type);
		rootJSON.put("compName",server_name);
		if(stype != null && stype != "")
		{
			rootJSON.put("hostIp",hostip);
		}

		//String fwdPage = "EgResults.jsp";
		//if(!StringUtils.isNull(treeViewSrc))
		//{
			//if(fwdPage.indexOf("EgResults.jsp?")!=-1)
			//{
				//fwdPage+="&from=ManUnMan";
			//}
			//else
			//{
				//fwdPage+="?from=ManUnMan";
			//}
		//}
		if(modifying)
		{
			if(remoteAgent != null)
			{
				session.setAttribute("prevSelectedRemAgents",remoteAgent);
			}
			if(selExtAgents != null)
			{
				session.setAttribute("prevSelectedExtAgents",selExtAgents);
			}
		}
		else
		{
			if(remoteAgent != null)
			{
				session.setAttribute("prevSelectedRemAgents",remoteAgent);
			}
			if(selExtAgents != null)
			{
				session.setAttribute("prevSelectedExtAgents",selExtAgents);
			}
		}
	}
	out.println(rootJSON);

%>



