<%@ include file="EgMonitorTracker.jsp" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@ page import ="egurkha.EgUIUtils"%>
<%@ page import = "com.egurkha.monitor.remotecontrol.PreAgentInfo" %>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.EgStateManager"%>
<%@ page import = "com.eg.EgManagersIniForManager"%>
<%@ page import = "com.eg.SMClusterHelper"%>
<%@ page import = "com.eg.PMClusterHelper"%>
<%@ page import = "com.egurkha.User" %>
<%@ page import = "com.egurkha.UserRegistry" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import="com.eg.AgentConfig" %>
<%@ page import="com.eg.EgDiscInfo" %>
<%@ page import="com.egurkha.util.StringUtils" %>
<%@ page import="net.sf.json.JSONObject" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="com.eg.EgURLDecoder"%>
<%@ page import="com.eg.supermanager.SMRemoteControlHelper"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import ="com.eg.EgCrypt"%>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	UserRegistry registry = UserRegistry.getInstance();
	String sessionId = null;
	if(from_sm)
	{
		sessionId = sessionId_sm;
	}
	else
	{
		sessionId = session.getId();
	}
	User this_user = registry.getUser(sessionId);
	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);

		newMode = "";
		controlModeOnManager = (String)session.getAttribute("controlModeOnManager");
		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");
	String fromDashBoardLayerModel=request.getParameter("fromDashBoardLayerModel");
	//out.println(agentsNotRunning);

	IniFile servicesIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String allowQualifiedHostNames = servicesIniFile.getValue("MISC_ARGS","AllowQualifiedHostNames");
	allowQualifiedHostNames = StringUtils.isNull(allowQualifiedHostNames)?"yes":allowQualifiedHostNames.trim();
	JSONObject json = new JSONObject();
	String isJsonResp = request.getParameter("isJsonResp");
	if(agentsNotRunning.contains(agentID))
	{
		//direct to ControlAgents
		String errMessage = "Agent is not running";
		//response.sendRedirect("/final/monitor/ControlAgents.jsp?errMessage="+errMessage);
		String ur = "ControlAgents.jsp?errMessage="+errMessage;
		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("") )    )
		{
		    //direct to DispInfo
		    //response.sendRedirect("/final/monitor/DispAgentInfo.jsp?agentIP="+agentID+"&agentMode="+newMode);
			String ur = "DispAgentInfo.jsp?agentIP="+agentID+"&agentMode="+newMode;

			if(isJsonResp!=null && isJsonResp.equals("true"))
			{
				json.put("newMode","true");
				json.put("forwardUrl",ur);
			}
			else
			{
%>
			<jsp:forward page="<%=ur%>" />
<%
			}
		}
		else
		{
			json.put("newMode","false");
			if(!EgInstallInfo.isSuperManager)
			{
				ini_controls= new IniFile(EgInstallInfo.getInstallDir() + sep + "manager" + sep + "config" + sep + "eg_controls.ini",true);
			}
			String userName = "";
			String passWord = "";

			//userName = request.getParameter("txtUserName");
			//passWord = request.getParameter("txtPassWord");

			if(userName.equals(""))
				userName="null";
			if(passWord.equals(""))
				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 timeStamp = request.getParameter("txtTimeStamp");
			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";
				}
				
			}						
			//out.println(mode+"  "+agentID+"   "+userName+"   "+passWord+"   "+cmd+"    "+responseType);
			//out.println("<br>");
			//cmd = cmd.replace('#','@');
			//out.println(mode+"  "+agentID+"   "+userName+"   "+passWord+"   "+cmd+"    "+responseType);
			//out.println("<br>");
			if(responseType.equalsIgnoreCase("yes"))
			{
				responseType="Y";
			}
			else
			{
				responseType="N";
			}

			//out.println(mode+"  "+agentID+"   "+userName+"   "+passWord+"   "+cmd+"    "+responseType);
			//out.println("<br>");
			AgentConfig agentConfig =  AgentConfig.getAgentConfig();
			EgDiscInfo discInfo = new EgDiscInfo("manager");
			String filePath="";
			File f = null;
			String localAgentStr = (String)session.getAttribute("localAgent");
			ArrayList RC_OUTPUT = new ArrayList();
			localAgentStr = StringUtils.isNull(localAgentStr)?"local":localAgentStr.trim();
			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(session.getId());
				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)session.getAttribute("SMIP");
					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
			{
				String val = timeout+"@#@"+passWord+"@#@"+cmd+"@#@"+responseType;
				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)
			{
				ini_controls.saveFile(); 			//save the ini file
			}
			long timeLapse =0;
			long totSleepTime=0;
			if(timeout == null || timeout.equals(""))
			{
				totSleepTime = 50000;
			}
			else
			{
		//		Long tmp = Long.parseLong(timeout);
				try{
				totSleepTime =  Long.parseLong(timeout)*1000; //tmp.longValue();
				}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.");
								//out.println("File not found");
								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",this_user.getLoginID());
					auditLogThread.setValue("Host_ip",this_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("Agent Mode",mode);
					
					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 class='f11-normal whiteColorText' style='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>");
							}

							//out.print(value);
							max = 150; 
						}
					}
					sbResults.append("</ul>");
				}
				else
				{
					timeLapse =0;					
					AuditLogThread auditLogThread = new AuditLogThread();	
					auditLogThread.setValue("User_id",this_user.getLoginID());
					auditLogThread.setValue("Host_ip",this_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("Agent Mode",mode);
					
					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 //if responseType.equalsIgnoreCase("N")
			{
				//display message page
				sbResults = new StringBuffer(1024);
				timeLapse =0;
				AuditLogThread auditLogThread = new AuditLogThread();	
				auditLogThread.setValue("User_id",this_user.getLoginID());
				auditLogThread.setValue("Host_ip",this_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("Agent Mode",mode);
				
				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());
	}
%>
