<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import="com.eg.*"%>
<%@ page import="com.eg.supermanager.*"%>
<%@ page import="com.egurkha.*"%>
<%@ page import="com.egurkha.admin.AuditLogThread"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="com.egurkha.monitor.remotecontrol.PreAgentInfo"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import ="egurkha.EgUIUtils"%>
<%@ taglib prefix="egui" uri="../../../WEB-INF/eg-taglib.tld" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);

	IniFile ini_controls = null;
	String mode =request.getParameter("agentMode");
	String agentOS = EgURLDecoder.decode(request.getParameter("agentOS"),"UTF-8");	
	String agentID = EgURLDecoder.decode(request.getParameter("agentIP"),"UTF-8");
	String newMode= null;
	List agentsNotRunning = null;
	String controlModeOnManager = null;
	if(EgInstallInfo.isSuperManager)
	{
		Hashtable paramsHt = new Hashtable();
		paramsHt.put("operation","getAgentMode");
		paramsHt.put("agentID",agentID);
		ArrayList managerIDs = EgElementInfo.getInstance().getManagerIDs("component",agentID);
		if(managerIDs != null && !managerIDs.isEmpty())
		{
			newMode = "";
			controlModeOnManager = (String)managerIDs.get(0);
			paramsHt.put("managerId",controlModeOnManager);
			SMRemoteControlHelper remoteControlFromSMHelper = new SMRemoteControlHelper();
			Hashtable resultHt = (Hashtable)remoteControlFromSMHelper.getResult(paramsHt);
			if(resultHt != null && resultHt.containsKey("agentMode"))
			{
				Object newModeInManager = resultHt.get("agentMode");
				if(newModeInManager != null && newModeInManager.toString().trim().length()>0)
				{
					newMode = (String)newModeInManager;
				}
			}
			if(newMode != null && (!newMode.equals(mode) || newMode.equals("")))
			{
				IniFile controlsFilePtrWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_controls.ini");
				controlsFilePtrWr.deleteValue("CURRENT_CONTROLS",agentID);
				controlsFilePtrWr.saveFile();
				EgConfigFilesSync.releaseInstance(controlsFilePtrWr);
			}
			if(resultHt.containsKey("agentsNotRunning"))
			{
				agentsNotRunning = (Vector)resultHt.get("agentsNotRunning");
			}
			else
			{
				agentsNotRunning = new Vector();
			}
		}
	}
	else
	{
		newMode = PreAgentInfo.getAgentMode(agentID);
		agentsNotRunning = (List)EgStateManager.notRunningAgents;
	}
	String sep = System.getProperty("file.separator");
	JSONObject json = new JSONObject();
	String isJsonResp = request.getParameter("isJsonResp");
	if(agentsNotRunning.contains(agentID))
	{
		String errMessage = "Agent is not running.";
		json.put("errorMessage",errMessage);
		if(EgInstallInfo.isSuperManager)
		{
			IniFile controlsFilePtrWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_controls.ini");
			controlsFilePtrWr.deleteValue("CURRENT_CONTROLS",agentID);
			controlsFilePtrWr.saveFile();
			EgConfigFilesSync.releaseInstance(controlsFilePtrWr);
		}
	}
	else
	{
		StringBuffer sbResults = null;
		json.put("errorMessage","-");
		if(newMode != null && ( !newMode.equals(mode) || newMode.equals("")))
		{
			String ur = "/final/admin/EgServerList.jsp?reqfrom=navlink&from_remote_control_page=true&s_agent_type="+request.getParameter("agent_type");
			json.put("newMode","true");
			json.put("forwardUrl",ur);
		}
		else
		{
			json.put("newMode","false");
			String userName="null";
			String passWord="null";
			String cmd = request.getParameter("txtCmd");
			cmd = EgUIUtils.decodeSecurityChar(cmd);				
			if(cmd.indexOf("ping") > -1 && agentOS.equals("HPUX"))
			{
				cmd = cmd + " -n 5";					
			}
			else if(cmd.indexOf("dir") == 0)
			{			
				int dirIndex = cmd.indexOf("dir ");
				String tmpArgument = cmd.substring(dirIndex+4);				
				if(tmpArgument.indexOf("\"") < 0)
					tmpArgument = "\""+tmpArgument+"\"";				
				tmpArgument = EgCrypt.encrypt(tmpArgument);
				cmd = "dir "+tmpArgument;				
			}    			
			String responseType = request.getParameter("response");
			String timeout = request.getParameter("txtTimeout");
			String currSelCmd=request.getParameter("selCmd");
			if(currSelCmd!=null && !currSelCmd.equalsIgnoreCase("") && !currSelCmd.equalsIgnoreCase("null"))
			{
				if(currSelCmd.equals("-1"))
				{
					currSelCmd="Please select a command";
				}
				else if(currSelCmd.equals("-2"))
				{
					currSelCmd="Other";
				}
			}
			if(responseType.equalsIgnoreCase("yes"))
			{
				responseType="Y";
			}
			else
			{
				responseType="N";
			}
			String filePath="";
			File f = null;
			String localAgentStr = new RemoteControlTaskHelper().getAgentReportingStatus(agentID);
			ArrayList RC_OUTPUT = new ArrayList();
			if(EgInstallInfo.isSuperManager)
			{
				Hashtable paramHt = new Hashtable();
				paramHt.put("operation","executeCommand");
				paramHt.put("agentID",agentID);
				paramHt.put("password","");
				paramHt.put("command",cmd);
				if(controlModeOnManager != null)
				{
					paramHt.put("managerId",controlModeOnManager);
				}
				StringBuffer buffer = new StringBuffer();
				buffer.append(sessionID);
				buffer.append(System.currentTimeMillis());
				paramHt.put("sessionId",buffer.toString());
				SMRemoteControlHelper remoteControlFromSMHelper = new SMRemoteControlHelper();
				Object obj = remoteControlFromSMHelper.getResult(paramHt);
				if(obj != null && obj instanceof ArrayList)
				{
					RC_OUTPUT = (ArrayList)obj;
				}
			}
			else if(localAgentStr != null && (localAgentStr.equals("priTosec") || localAgentStr.equals("secTopri")))
			{
				String val = timeout+"@#@"+passWord+"@#@"+cmd+"@#@"+responseType;
				if(localAgentStr.equals("priTosec"))
				{
					String secondaryManagerIP = (String)EgManagersIniForManager.getInstance().getSecondaryManagers().get(0);
					PMClusterHelper pm = new PMClusterHelper();
					pm.executeRemoteControlInSecondaryManager(agentID, "RemoteControl:"+sessionID,val,secondaryManagerIP);
				}
				else
				{
					SMClusterHelper sm = new SMClusterHelper();
					sm.executeRemoteControlInPrimaryManager(agentID,"RemoteControl:"+sessionID,val);
				}
				filePath = EgInstallInfo.getInstallDir()+ sep +"tmp"+ sep + agentID + "_" + sessionID+".RemoteControl";
				f = new File(filePath);
				if(f.exists())
				{
					f.delete();
				}
			}
			else
			{
				if(!EgInstallInfo.isSuperManager)
				{
					String val = timeout+"@#@"+passWord+"@#@"+cmd+"@#@"+responseType;
					ini_controls= EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+sep+"manager"+sep+"config"+sep+"eg_controls.ini");
					ini_controls.setValue(agentID,"RemoteControl:"+ sessionID,val);	//write the commands in
				}
				filePath = EgInstallInfo.getInstallDir()+sep+"tmp"+sep+agentID+"_"+sessionID+".RemoteControl";
				f = new File(filePath);
				if(f.exists())
				{
					f.delete();
				}
			}
			if(!EgInstallInfo.isSuperManager)
			{
				if(ini_controls != null)
				{
					ini_controls.saveFile();
					EgConfigFilesSync.releaseInstance(ini_controls);
				}
			}
			long timeLapse =0;
			long totSleepTime=0;
			if(timeout == null || timeout.equals(""))
			{
				totSleepTime = 50000;
			}
			else
			{
				try
				{
					totSleepTime =  Long.parseLong(timeout)*1000;
				}
				catch(Exception ex)
				{
					ex.printStackTrace();
				}
			}
			totSleepTime += 4000; // if the user set timeout as x seconds in UI, we make the user to wait for x+4 seconds. so that agent will finish the task comfortably with in that x seconds.
			long sleepTime = 1000;
			Vector result = new Vector();
			if(responseType.equalsIgnoreCase("y"))
			{
				if(!EgInstallInfo.isSuperManager)
				{
					while(true)
					{
						f  = new File(filePath);
						if(f != null && f.exists())
						{
							BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f),"UTF-8"));
							String line = null;
							while((line=br.readLine()) != null)
							{
								if(localAgentStr.equals("local"))
								{
									result.add(line);
								}
								else
								{
									result.add(com.eg.EgCrypt.decrypt(line));
								}
							}
							//delet the file
							br.close();

							if(EgInstallInfo.isClusterSupported)
							{
								//upload the result file to all other managers
								EgManagersIniForManager mi = EgManagersIniForManager.getInstance();
								if(mi.isPrimaryManager())
								{

									PMClusterHelper pm = new PMClusterHelper();
									pm.deleteResultFile(f.getName()); //send the details to secondary managers
								}
								else
								{

									SMClusterHelper sm = new SMClusterHelper();
									sm.deleteResultFile(f.getName()); //send the details to other managers
								}
							}
							f.delete();
							break;
						}
						else
						{
							if(timeLapse <= totSleepTime)
							{
								timeLapse += sleepTime;
								Thread.currentThread().sleep(sleepTime);
							}
							else
							{
								result.add("The agent is not responding.");
								break;
							}
						}


					}
				}
				if(RC_OUTPUT != null && !RC_OUTPUT.isEmpty())
				{
					result.addAll(RC_OUTPUT);
				}
				sbResults = new StringBuffer(1024);
				if(result != null && result.size() > 0)
				{
					timeLapse =0;
					AuditLogThread auditLogThread = new AuditLogThread();
					auditLogThread.setValue("User_id",_user.getLoginID());
					auditLogThread.setValue("Host_ip",_user.getUserIP(sessionID));
					auditLogThread.setValue("Session_id",sessionID);
					auditLogThread.setValue("Category","Monitor");
					auditLogThread.setValue("Module","Remote Control");
					auditLogThread.setValue("Activity","Execute Command");

					auditLogThread.setCurrentValue("Agent Ip/Nick Name",agentID);
					auditLogThread.setCurrentValue("Selected Command",currSelCmd);
					String currArguments=request.getParameter("arguments");
					if(currArguments!=null && !currArguments.equalsIgnoreCase("") && !currArguments.equalsIgnoreCase("null") && !currArguments.equalsIgnoreCase("none"))
					{
						auditLogThread.setCurrentValue("Arguments",currArguments);
					}
					String currTxtCmd1=request.getParameter("txtCmd1");
					if(currTxtCmd1!=null && !currTxtCmd1.equalsIgnoreCase("") && !currTxtCmd1.equalsIgnoreCase("null"))
					{
						auditLogThread.setCurrentValue("Command",currTxtCmd1);
					}
					if(responseType.equals("Y"))
					{
						auditLogThread.setCurrentValue("Output Required","Yes");
					}
					else
					{
						auditLogThread.setCurrentValue("Output Required","No");
					}
					if(timeout!=null && !timeout.equalsIgnoreCase("null") && !timeout.equals(""))
					{
						auditLogThread.setCurrentValue("Time Out",timeout);
					}
					auditLogThread.setValue("Description","Remote control command issued");
					auditLogThread.sendItToDB();

					sbResults.append("<ul  style='font-size:11px;font-weight:bold;color:#fff;margin:10px'>");

					int max=150;

					if(result != null &&  result.size() > 0)
					{
						String value = "";
						String sub1 = null;
						String sub2 = null;

						for(int i=0;i<result.size();i++)
						{
							value = (String)result.get(i);

							int ind=0;
							while((ind=value.indexOf('<')) > -1 )
							{
								sub1 = value.substring(0,ind);
								sub2 = value.substring(ind+1,value.length());
								value = sub1 + "&lt;" + sub2;
							}

							while((ind=value.indexOf('>')) > -1 )
							{
								sub1 = value.substring(0,ind);
								sub2 = value.substring(ind+1,value.length());
								value = sub1 + "&gt;" + sub2;
							}

							if(value.length() >300 )
							{
								max=130;
							}

							while(value.length() > max)
							{
								sbResults.append("<li>"+ value.substring(0,max) + "</li>");
								value =value.substring(max,value.length());
							}
							if(value.length() <= max)
							{
								sbResults.append("<li>"+value+ "</li>");
							}
							max = 150;
						}
					}
					sbResults.append("</ul>");
				}
				else
				{
					timeLapse =0;
					AuditLogThread auditLogThread = new AuditLogThread();
					auditLogThread.setValue("User_id",_user.getLoginID());
					auditLogThread.setValue("Host_ip",_user.getUserIP(sessionID));
					auditLogThread.setValue("Session_id",sessionID);
					auditLogThread.setValue("Category","Monitor");
					auditLogThread.setValue("Module","Remote Control");
					auditLogThread.setValue("Activity","Execute Command");

					auditLogThread.setCurrentValue("Agent Ip/Nick Name",agentID);
					auditLogThread.setCurrentValue("Selected Command",currSelCmd);
					String currArguments=request.getParameter("arguments");
					if(currArguments!=null && !currArguments.equalsIgnoreCase("") && !currArguments.equalsIgnoreCase("null") && !currArguments.equalsIgnoreCase("none"))
					{
						auditLogThread.setCurrentValue("Arguments",currArguments);
					}
					String currTxtCmd1=request.getParameter("txtCmd1");
					if(currTxtCmd1!=null && !currTxtCmd1.equalsIgnoreCase("") && !currTxtCmd1.equalsIgnoreCase("null"))
					{
						auditLogThread.setCurrentValue("Command",currTxtCmd1);
					}
					if(responseType.equals("Y"))
					{
						auditLogThread.setCurrentValue("Output Required","Yes");
					}
					else
					{
						auditLogThread.setCurrentValue("Output Required","No");
					}
					if(timeout!=null && !timeout.equalsIgnoreCase("null") && !timeout.equals(""))
					{
						auditLogThread.setCurrentValue("Time Out",timeout);
					}
					auditLogThread.setValue("Description","Remote control command issued");
					auditLogThread.sendItToDB();
					sbResults.append("<ul  style='font-family: Tahoma, Arial, sans-serif;font-size:11px; font-weight:bold;color:#fff;margin:10px'><li>");
								sbResults.append("Agent did not respond");
						sbResults.append("</li>");
					sbResults.append("</ul>");
				}
			}
			else
			{
				sbResults = new StringBuffer(1024);
				timeLapse =0;
				AuditLogThread auditLogThread = new AuditLogThread();
				auditLogThread.setValue("User_id",_user.getLoginID());
				auditLogThread.setValue("Host_ip",_user.getUserIP(sessionID));
				auditLogThread.setValue("Session_id",sessionID);
				auditLogThread.setValue("Category","Monitor");
				auditLogThread.setValue("Module","Remote Control");
				auditLogThread.setValue("Activity","Execute Command");

				auditLogThread.setCurrentValue("Agent Ip/Nick Name",agentID);
				auditLogThread.setCurrentValue("Selected Command",currSelCmd);
				String currArguments=request.getParameter("arguments");
				if(currArguments!=null && !currArguments.equalsIgnoreCase("") && !currArguments.equalsIgnoreCase("null") && !currArguments.equalsIgnoreCase("none"))
				{
					auditLogThread.setCurrentValue("Arguments",currArguments);
				}
				String currTxtCmd1=request.getParameter("txtCmd1");
				if(currTxtCmd1!=null && !currTxtCmd1.equalsIgnoreCase("") && !currTxtCmd1.equalsIgnoreCase("null"))
				{
					auditLogThread.setCurrentValue("Command",currTxtCmd1);
				}
				if(responseType.equals("Y"))
				{
					auditLogThread.setCurrentValue("Output Required","Yes");
				}
				else
				{
					auditLogThread.setCurrentValue("Output Required","No");
				}
				if(timeout!=null && !timeout.equalsIgnoreCase("null") && !timeout.equals(""))
						auditLogThread.setCurrentValue("Time Out",timeout);

				auditLogThread.setValue("Description","Remote control command issued");
				auditLogThread.sendItToDB();
				sbResults.append("<ul  style='font-family: Tahoma, Arial, sans-serif;font-size:11px; font-weight:bold;color:#fff;margin:10px'><li>");
						sbResults.append("command successfully registered ...");
					sbResults.append("</li>");
				sbResults.append("</ul>");
			}
			if(sbResults!=null)
			{
				json.put("output",sbResults.toString());
			}
			else
			{
				json.put("output","-");
			}
		}
	}
	if(isJsonResp!=null && isJsonResp.equals("true"))
	{
		response.setContentType("application.json;charset=UTF-8");
		response.getWriter().write(json.toString());
	}
%>



