<%@ include file="EgMonitorTracker.jsp" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@ 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.eg.AgentConfig" %>
<%@ page import="com.eg.EgDiscInfo" %>
<%@ page import="com.eg.RemoteControlTaskHelper" %>
<%@ 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="net.sf.json.*"%>
<%@ page import ="egurkha.EgUIUtils"%>
<%@ page import ="com.eg.EgCrypt"%>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	//response.setContentType("application.json;charset=UTF-8");
	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 agentID = EgURLDecoder.decode(request.getParameter("agentIP"),"UTF-8");
	String agentOS= EgURLDecoder.decode(request.getParameter("agentOS"),"UTF-8");
	String compNick  = EgURLDecoder.decode(request.getParameter("hostName"),"UTF-8");
	String isAgentBased = EgURLDecoder.decode(request.getParameter("isAgentBased"),"UTF-8");
	String rmtOrExtAgentIp = EgURLDecoder.decode(request.getParameter("rmtOrExtAgentIp"),"UTF-8");
	String userSessionID = request.getParameter("user_session_id");
	String displayTxtCmd = request.getParameter("displayTxtCmd");	
	String newMode= null;
	List agentsNotRunning = null;
	String controlModeOnManager = null;
	String outputColorCode = "";
	String imgPath = "";
	if("false".equals(isAgentBased))
		compNick = rmtOrExtAgentIp;
	if(monitor_Skin.equalsIgnoreCase("Light"))
	{
		outputColorCode = "#2a292a";
		imgPath = "/final/images/Light";
	}
	else {
		outputColorCode = "#c6c6c6";
		imgPath = "/final/images/Dark";
	}
	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(compNick);
		agentsNotRunning = (List)EgStateManager.notRunningAgents;
	}
	String sep = System.getProperty("file.separator");
	String fromDashBoardLayerModel=request.getParameter("fromDashBoardLayerModel");

	IniFile servicesIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String allowQualifiedHostNames = servicesIniFile.getValue("MISC_ARGS","AllowQualifiedHostNames");
	
	IniFile uiIniFile = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	
	allowQualifiedHostNames = StringUtils.isNull(allowQualifiedHostNames)?"yes":allowQualifiedHostNames.trim();
	JSONObject json = new JSONObject();
	String isJsonResp = request.getParameter("isJsonResp");
	StringBuffer sbResults = null;
	if(agentsNotRunning.contains(compNick))
	{
		sbResults = new StringBuffer(1024);
		//direct to ControlAgents
		String errMessage = mappingInfo.getTextDescription("monitor.remotecontrol.Agent is not running");
		if(EgInstallInfo.isSuperManager)
		{
			IniFile controlsFilePtrWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_controls.ini");
			controlsFilePtrWr.deleteValue("CURRENT_CONTROLS",compNick);
			controlsFilePtrWr.saveFile();
			EgConfigFilesSync.releaseInstance(controlsFilePtrWr);
		}
		sbResults.setLength(0);
		sbResults.append("<ul style='margin:10px; width:100%; height:93%; display:table;' class='font_normal14'>");
		sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;'>");
		sbResults.append("<div>");
		sbResults.append("<img src='"+imgPath+"/error_msg_icon.png'>");
		sbResults.append("</div>");
		sbResults.append("<div style='margin-top:15px;'><span style='color:"+outputColorCode+";'>");
										
		sbResults.append(errMessage);
		sbResults.append("</span></div>");
		sbResults.append("</div>");
		sbResults.append("</ul>");
		if(sbResults!=null)
			json.put("output",sbResults.toString());
		json.put("errorMessage","-");
	}
	else
	{
		sbResults = new StringBuffer(1024);
		json.put("errorMessage","-");
		
		RemoteControlTaskHelper helper = new RemoteControlTaskHelper();
		helper.noControlModeSleep = true;
		if(helper.setAgentIntoControlMode(compNick))
		{
			if(!EgInstallInfo.isSuperManager)
			{
				ini_controls= new IniFile(EgInstallInfo.getInstallDir() + sep + "manager" + sep + "config" + sep + "eg_controls.ini",true);
			}
			String userName = "";
			String passWord = "";

			if(userName.equals(""))
				userName="null";
			if(passWord.equals(""))
				passWord="null";

			String cmd = request.getParameter("txtCmd");
			cmd = EgUIUtils.decodeSecurityChar(cmd);		
			String responseType = request.getParameter("response");
			String timeout = request.getParameter("txtTimeout");
			String currSelCmd=request.getParameter("selCmd");
			String show_instance_str = request.getParameter("show_instance_str");
			if(displayTxtCmd.equals("List files in a directory"))
			{
				int dirIndex = cmd.indexOf("dir ");
				String tmpArgument = cmd.substring(dirIndex+4);				
				if(tmpArgument.indexOf("\"") < 0)
					tmpArgument = "\""+tmpArgument+"\"";				
				tmpArgument = EgCrypt.encrypt(tmpArgument);
				cmd = "dir "+tmpArgument;
			}
			if(cmd != null && cmd.startsWith("typeperf") && show_instance_str != null && show_instance_str.equalsIgnoreCase("true"))
			{
				cmd="typeperf -qx -y";
				currSelCmd="typeperf -qx -y";
			}
			else if((cmd.indexOf("ping") > -1) && agentOS.equals("HPUX"))
			{
				cmd = cmd + " -n 5";
			}	
			String gridTitle = "";
			boolean drawTable = false;
			if(currSelCmd!=null && !currSelCmd.equalsIgnoreCase("") && !currSelCmd.equalsIgnoreCase("null"))
			{
				if(currSelCmd.equals("-1"))
				{
					currSelCmd=mappingInfo.getTextDescription("monitor.remotecontrol.Please select a command");
				}
				else if(currSelCmd.equals("-2"))
				{
					currSelCmd=mappingInfo.getTextDescription("admin.ic.Other");
				}
			}
			if(responseType.equalsIgnoreCase("yes"))
			{
				responseType="Y";
			}
			else
			{
				responseType="N";
			}

			AgentConfig agentConfig =  AgentConfig.getAgentConfig();
			EgDiscInfo discInfo = new EgDiscInfo("manager");
			String filePath="";
			File f = null;
			String localAgentStr = helper.getAgentReportingStatus(compNick);
			ArrayList RC_OUTPUT = new ArrayList();
			if(EgInstallInfo.isSuperManager)
			{
				Hashtable paramHt = new Hashtable();
				paramHt.put("operation","executeCommand");
				paramHt.put("agentID",compNick);
				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+"@#@y";
				if(localAgentStr.equals("priTosec"))
				{
					String secondaryManagerIP = (String)EgManagersIniForManager.getInstance().getSecondaryManagers().get(0);
					PMClusterHelper pm = new PMClusterHelper();
					pm.executeRemoteControlInSecondaryManager(compNick, "RemoteControl:"+sessionId,val,secondaryManagerIP);
				}
				else
				{
					SMClusterHelper sm = new SMClusterHelper();
					sm.executeRemoteControlInPrimaryManager(compNick,"RemoteControl:"+sessionId,val);
				}

				filePath = EgInstallInfo.getInstallDir()+ sep +"tmp"+ sep + compNick + "_" + sessionId+".RemoteControl";
				f = new File(filePath);
				if(f.exists())
				{
					f.delete();
				}
			}
			else
			{
				String val = timeout+"@#@"+passWord+"@#@"+cmd+"@#@y";
				ini_controls.setValue(compNick,"RemoteControl:"+ sessionId,val);	//write the commands in 

				filePath = EgInstallInfo.getInstallDir()+ sep +"tmp"+ sep + compNick + "_" + 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 = 50; 
			Vector result = new Vector();
			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((mappingInfo.getTextDescription("monitor.remotecontrol.Agent time out")+"."+mappingInfo.getTextDescription("admin.error.Please try again")+"."));
							break;
						}
					}
				}
			}
			if(RC_OUTPUT != null && !RC_OUTPUT.isEmpty())
			{
				result.addAll(RC_OUTPUT);
			}
			String resultStr = result.toString();
			if(result != null && !result.isEmpty() && resultStr.indexOf("time out") == -1)
			{
				if(responseType.equalsIgnoreCase("y"))
				{
					if(result != null && result.size() > 0)
					{
						if(!currSelCmd.equals("netstat -rn") && (currSelCmd.startsWith("netstat") && result.size() > 1 && !result.get(1).toString().trim().startsWith("NETSTAT")) )
						{
							drawTable = true;
						}
						if(currSelCmd.startsWith("wmic"))
						{
							String tmp = result.get(0).toString().trim();
							if(tmp.startsWith("BuildNumber"))
								drawTable = true;
						}
						if(resultStr.indexOf("OUTPUT ERROR")>-1){
							result.remove(0);
						}
						else if((currSelCmd.equalsIgnoreCase("net file") || currSelCmd.equalsIgnoreCase("net share")) && !(result.get(0).toString().indexOf("There are no entries in the list")>-1))
						{
							drawTable = true;
							result.remove(result.size()-1);
						}
						timeLapse =0;
						sbResults.append("<ul  style='width:100%; height:100%; display:table;' class='font_normal14'>");
						int max=300;
						if(result != null &&  result.size() > 0)
						{
							String value = "";
							String sub1 = null;
							String sub2 = null;
							JSONArray gridValues = new JSONArray();
							JSONObject gridJson = new JSONObject();
							JSONArray colArr = new JSONArray();
							for(int i=0;i<result.size();i++)
							{
								value = (String)result.get(i);
								JSONObject gridJsonObj = new JSONObject();
								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;
								}
								if(drawTable)
								{
									//JSONObject gridJson = new JSONObject();
									int colIdx=0;
									value=value.trim();
									if(value.endsWith("^^"))
										value=value+"-";
									value = StringUtils.replace(value," name","_name");
									value = StringUtils.replace(value," Address","_Address");
									value = StringUtils.replace(value,"# Locks","Locks");
									String arr[] = StringUtils.getTokens(value," ");
									
									if(currSelCmd.equalsIgnoreCase("net file") || currSelCmd.equalsIgnoreCase("net share") || currSelCmd.startsWith("wmic"))
									{
										if(currSelCmd.startsWith("wmic")){
											gridTitle = mappingInfo.getTextDescription("monitor.remotecontrol.OS List");
										}
										else {
											gridTitle = mappingInfo.getTextDescription("monitor.remotecontrol.List of files");
										}
										if(i==0)
										{
											for(int j=0;j<arr.length;j++) {
												colArr.add(StringUtils.replace(arr[j],"_"," "));
											}
										}
										else
										{
											for(int j=0;j<arr.length;j++) {
												gridJsonObj.put("COLUMVal_"+(colIdx++),arr[j]);
											}
											gridValues.add(gridJsonObj);
										}
									}
									else if(currSelCmd.startsWith("netstat"))
									{
										if(i==0)
										{
											gridTitle = value;
										}
										else if(i==1)
										{
											for(int j=0;j<arr.length;j++) {
												colArr.add(StringUtils.replace(arr[j],"_"," "));
											}
										}
										else
										{
											for(int j=0;j<arr.length;j++) {
												gridJsonObj.put("COLUMVal_"+(colIdx++),arr[j]);
											}
											gridValues.add(gridJsonObj);
										}
									}
									if(gridValues.size()>0){
										gridJson.put("tableColumns",colArr);
										gridJson.put("gridTitle",gridTitle);
										gridJson.put("gridValues",gridValues);
										json.put("isGridView","true");
										json.put("gridJson",gridJson);
									}
									else {
										sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;'>");
										sbResults.append("<div>");
										sbResults.append("<img src='"+imgPath+"/info_mgs_icon.png'>");
										sbResults.append("</div>");
										sbResults.append("<div style='margin-top:15px;'><span style='color:"+outputColorCode+";'>");
										sbResults.append(mappingInfo.getTextDescription("monitor.common.No data found"));
										sbResults.append("</span></div>");
										sbResults.append("</div>");
									}
								}
								else
								{
									if(value.indexOf("There are no entries in the list")>-1)
									{
										sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;'>");
										if(value.startsWith("Info:"))
											value = value.substring(value.indexOf("Info:"));
										sbResults.append("<div>");
										sbResults.append("<img src='"+imgPath+"/info_mgs_icon.png'>");
										sbResults.append("</div>");
										sbResults.append("<div style='margin-top:15px;'><span style='color:"+outputColorCode+";'>");
										sbResults.append(value+"</span></div>");
									}
									else{
										if(i==0)
											sbResults.append("<div style='text-align:left;margin:10px;'>");
										while(value.length() > max)
										{
											sbResults.append("<li><pre>"+ value.substring(0,max) + "</pre></li>");
											value =value.substring(max,value.length());
										}
										if(value.length() <= max)
										{
											sbResults.append("<li><pre>"+value+ "</pre></li>");
										}
									}
								}
								max = 150; 
							}
							sbResults.append("</div>");
						}
						sbResults.append("</ul>");
					}
					else
					{
						timeLapse =0;
						sbResults.append("<ul  style='margin:10px' class='font_normal14'><li>");
						sbResults.append(mappingInfo.getTextDescription("monitor.remotecontrol.Agent did not respond"));
						sbResults.append("</li>");
						sbResults.append("</ul>");
					}
				}
				else //if responseType.equalsIgnoreCase("N")
				{
					sbResults = new StringBuffer(1024);
					timeLapse =0;
					sbResults.append("<ul  style='width:95%; height:93%; display:table;' class='font_normal14'>");
					if((resultStr.indexOf("Exception")>-1) || (resultStr.indexOf("OUTPUT ERROR")>-1) || (resultStr.indexOf("time out")>-1)){
						if(result.size()< 4){
							sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;'>");
							sbResults.append("<div>");
							sbResults.append("<img src='"+imgPath+"/error_msg_icon.png'>");
							sbResults.append("</div>");
							sbResults.append("<div style='margin-top:15px;'><span style='color:"+outputColorCode+";'>");
							}
						else{
							sbResults.append("<div>");
							sbResults.append("<div style='text-align:left;margin:10px;'>");
						}										
						for(int i=1;i<result.size();i++)
						{
							String value = (String)result.get(i);
							sbResults.append("<li>"+value+"</li>");
						}
						sbResults.append("</div>");
					}
					else {
						sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;' class='font_normal14'>");
						//display message page
						sbResults.append("<div>");					
						sbResults.append("<img src='"+imgPath+"/success_msg_icon.png'>");
						sbResults.append("</div>");
						sbResults.append("<div style='margin-top:15px;' class='font_normal14'><span >");
						displayTxtCmd = request.getParameter("displayTxtCmd");
						if(displayTxtCmd!=null && !displayTxtCmd.equalsIgnoreCase("") && !displayTxtCmd.equalsIgnoreCase("null") && !displayTxtCmd.equalsIgnoreCase("Other"))
						{
							sbResults.append((mappingInfo.getTextDescription("monitor.remotecontrol.The Remote control action")+" '"+displayTxtCmd+"' "+mappingInfo.getTextDescription("monitor.remotecontrol.completed successfully")));
						}
						else {
							sbResults.append(mappingInfo.getTextDescription("monitor.remotecontrol.The Remote control action completed successfully"));
						}
						sbResults.append("</span></div>");
					}
					
					sbResults.append("</div>");
					sbResults.append("</ul>");
				}
			}
			else {
				sbResults.setLength(0);
				sbResults.append("<ul style='margin:10px; width:100%; height:93%; display:table;' class='font_normal14'>");
				sbResults.append("<div style='text-align:center; vertical-align:middle;display:table-cell;'>");
				sbResults.append("<div>");
				sbResults.append("<img src='"+imgPath+"/info_mgs_icon.png'>");
				sbResults.append("</div>");
				sbResults.append("<div style='margin-top:15px;' class='font_normal14'><span>");
				sbResults.append((mappingInfo.getTextDescription("monitor.remotecontrol.Agent time out")+"."+mappingInfo.getTextDescription("admin.error.Please try again")+"."));
				sbResults.append("</span></div>");
				sbResults.append("</div>");
				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());
	}
%>
