
<%
/**
 *	Name			:	EgManageAgents.jsp
 *	Purpose			:	This page enables the user to enable or disable agent auto upgrade
 */
%>

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

<%@ page import = "java.util.Vector"%>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Hashtable"%>
<%@ page import = "java.util.Enumeration"%>
<%@ page import = "java.util.StringTokenizer"%>
<%@ page import = "com.eg.AgentConfig" %>
<%@ page import = "com.eg.EgAgentInfo" %>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.egurkha.util.ArrayUtils"%>
<%@ 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();
	JSONObject hiddens = new JSONObject();
	rootJSON.put("success","true");

	String upgrade_status = request.getParameter("upgrade_status");
	String strSearch = request.getParameter("strSearch");
	boolean isSearchResult = (strSearch != null && !strSearch.equalsIgnoreCase(""));
	ArrayList searchList = new ArrayList();
	if (isSearchResult)
	{
		strSearch = egurkha.EgUIUtils.decodeSecurityChar(strSearch);
		StringTokenizer strTokens = new StringTokenizer(strSearch);
		while (strTokens.hasMoreTokens())
		{
			String thisToken = strTokens.nextToken().trim();
			if (thisToken.equals("")) continue;
			searchList.add(thisToken);
		}
	}

	EgAgentInfo ai = new EgAgentInfo("manager");
	AgentConfig agentConfig = AgentConfig.getAgentConfig();
	Vector agentListWithStatus = agentConfig.getUpgradeStatusForAllAgents();
	//Changed By Inbaraj
	IniFile servicesIniRead = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_services.ini");
	String fileName = "";
	String autoUpgradeInfo=servicesIniRead.getValue("MISC_ARGS","AutoUpgradeInfo");
	if(autoUpgradeInfo != null && !autoUpgradeInfo.equals("") && autoUpgradeInfo.equalsIgnoreCase("eg_autoupgrade"))
	{
		fileName = "eg_autoupgrade.ini";
	}
	else
	{
		fileName = "eg_tests.ini";
	}
	IniFile ini_read = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/"+ fileName);

	String defaultUpgradeValue=servicesIniRead.getValue("MISC_ARGS","DefaultAutoUpgrade");
	String old_interval = "";
	String alreadyEnabledAgents = "";
	session.setAttribute("ipString", agentListWithStatus);
	Hashtable agentList = new Hashtable(25);
	String agentName = "";
	String status = "";

	Hashtable versionHash = new Hashtable();
	Hashtable statusHash = new Hashtable();

	ArrayList agentToCheck = new ArrayList();

	for(int i=0;i<agentListWithStatus.size();i++)
	{
		StringTokenizer str1 = new StringTokenizer((String)agentListWithStatus.elementAt(i), ",");
		agentName = str1.nextToken();
		String agentVersion12 = agentConfig.getAgentVersion((String)agentName, false);
		status = str1.nextToken();
		StringTokenizer str2 = new StringTokenizer(agentName, ":");
		String ipStr = "";
		if (agentVersion12==null)
			continue;
		while(str2.hasMoreTokens())
		{
			ipStr = str2.nextToken();
			versionHash.put(ipStr,agentVersion12);
			statusHash.put(ipStr,status);
			agentToCheck.add(ipStr);
		}
	}
	ArrayList validAgents = ai.getValidAgentsFromList (agentToCheck);
	for (int i=0; i<validAgents.size(); i++)
	{
		String me = (String) validAgents.get(i);
		String st = (String) statusHash.get(me);
		String v = (String) versionHash.get(me);
		if (st != null && v != null)
		{
			me = me + "("+v+")";
			agentList.put(me,st);
		}
	}
	String s_key = "";
	String s_value = "";
	Enumeration agents;
	session.setAttribute("egPageDesc","EgManageAgents.jsp");

	String optionvalue = request.getParameter("optvalue");
	if(optionvalue == null)
		optionvalue="upgrade";

	rootJSON.put("tabSelected",optionvalue);
	JSONObject hiddenObj = new JSONObject();
	hiddens.put("optvalue",optionvalue);

	String [] upgradeagents ;

	if (!optionvalue.equalsIgnoreCase("interval"))
	{
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		ArrayList managedNicks = discInfo.getAllManagedNames();
		Set managedNicks_upperCase = new TreeSet();
		if(managedNicks != null)
		{
			int co=managedNicks.size();
			for(int i=0;i<co;i++)
			{
				managedNicks_upperCase.add(((String)managedNicks.get(i)).toUpperCase());
			}
		}
		EgExternalInfo externalInfo = new EgExternalInfo("manager");
		String exa[] = externalInfo.getAllExternalAgents();
		if(exa != null)
		{
			int size=exa.length;
			for(int i=0;i<size;i++)
			{
				managedNicks_upperCase.add(exa[i].toUpperCase());
			}
		}
		String rea[] = externalInfo.getAllRemoteAgents();
		if(rea != null)
		{
			int size=rea.length;
			for(int i=0;i<size;i++)
			{
				managedNicks_upperCase.add(rea[i].toUpperCase());
			}
		}
		String s_left_title = "AUTO UPGRADE ENABLED";
		String s_right_title="AUTO UPGRADE DISABLED";

		List leftAgents = new LinkedList();
		List rightAgents = new LinkedList();

		agents = agentList.keys();
		boolean alreadyInTheUpgradeList = false;
		Hashtable results = null; //agentConfig.getAllAgentDetails();
		while (agents.hasMoreElements())
		{
			s_key = (String)agents.nextElement();
			String keyWithoutVersion = s_key.substring(0,s_key.indexOf("("));
			if(!managedNicks_upperCase.contains(keyWithoutVersion.toUpperCase()))
			{
				continue;
			}
			if (optionvalue.equalsIgnoreCase("now"))
			{
				upgradeagents = ini_read.getVariables("UPGRADE_NOW");
				if( upgradeagents != null && upgradeagents.length > 0)
				{
					alreadyInTheUpgradeList = ArrayUtils.contains(upgradeagents, keyWithoutVersion);
					if(alreadyInTheUpgradeList)
					{
						leftAgents.add(s_key);
					}
					else
					{
						rightAgents.add(s_key);
					}
				}
				else
				{
					rightAgents.add(s_key);
				}
				if (results == null)
					results = agentConfig.getAllAgentDetails();
				String packId = (String) results.get(keyWithoutVersion); //agentConfig.getAgentDetails(keyWithoutVersion);
				if (packId == null)
				{
					Enumeration ee = results.keys();
					String search = ":"+keyWithoutVersion+":";
					String first = keyWithoutVersion+":";
					String last = ":"+keyWithoutVersion;
					while (ee.hasMoreElements())
					{
						String ss = (String) ee.nextElement();
						if (ss.startsWith(first) || ss.endsWith(last) ||
							ss.indexOf(search)>=0)
						{
							packId = (String) results.get(ss);
							break;
						}
					}
					if (packId == null)
					{
						continue;
					}
				}
				String[] tokens = StringUtils.getTokens(packId, EgConstants.COMMA);
				if (tokens[0].equalsIgnoreCase("false"))
				{
					rightAgents.remove(s_key);
				}
			}
			else
			{
				s_value = (String)agentList.get(s_key);
				if (s_value.equalsIgnoreCase("true"))
				{
					if (searchList !=null && searchList.size() > 0 && upgrade_status.equalsIgnoreCase("upgrade_enabled"))
					{
						if(isItemExists(searchList,s_key))
						{
							leftAgents.add(s_key);
						}
					}
					else
					{
						leftAgents.add(s_key);
					}
				}
				else
				{
					if (searchList !=null && searchList.size() > 0 && upgrade_status.equalsIgnoreCase("upgrade_disabled"))
					{
						if(isItemExists(searchList,s_key))
						{
							rightAgents.add(s_key);
						}
					}
					else
					{
						rightAgents.add(s_key);
					}
				}
			}
		}

		if(optionvalue.equalsIgnoreCase("now"))
		{
			s_left_title="AGENTS TO UPGRADE NOW";
			s_right_title="AUTO UPGRADEABLE AGENTS";

			String message = null;
			String mappingMsg = null;
			if (rightAgents.size() > 0)
			{
				mappingMsg = _mapping.getTextDescription("admin.upgrade.admin.upgrade.This page allows users to select the agents to be upgraded within the next 15 minutes");
				message = "<div style='height:100%;text-align:center;padding:10px'><img src='/final/images/spacer.gif' class='iconInfo' border='0' style='margin-right:0px;margin-top:-6px'>"+mappingMsg+".</div>";
			}
			else if (leftAgents.size() == 0)
			{
				mappingMsg = _mapping.getTextDescription("admin.upgrade.Auto upgrade is not enabled for any agent");
				message = "<div class='egFlexCenterByColumnWise' style='height:100%'><div class='iconInformation'></div><div class='commonErrorMsgText' id='noCompAlrtDiv'>"+mappingMsg+".</div></div>";
			}

			if (message != null)
			{
				rootJSON.put("upgradeNowMainMsg",message);
			}
		}

		Collections.sort(leftAgents,String.CASE_INSENSITIVE_ORDER);
		Collections.sort(rightAgents,String.CASE_INSENSITIVE_ORDER);
		if ((optionvalue.equalsIgnoreCase("now") && (leftAgents.size() > 0 || rightAgents.size() > 0))
			|| (optionvalue.equalsIgnoreCase("upgrade")))
		{
			Object[] left = leftAgents.toArray();
			Object[] right = rightAgents.toArray();

			rootJSON.put("leftSelectionTitle",_mapping.getTextDescription("admin.upgrade."+s_left_title));

			if (left.length > 0)
			{
				/* when we get version null we remove the null */
				String nullRemoved = (String)left[0];
				if(nullRemoved != null && nullRemoved.indexOf("(") !=-1)
				{
					String nullStr = nullRemoved.substring(nullRemoved.indexOf("(")+1,nullRemoved.indexOf(")"));
					if(nullStr !=null && nullStr.equalsIgnoreCase("null"))
						nullRemoved = nullRemoved.substring(nullRemoved.indexOf("("));

					if(nullRemoved.indexOf("(") > -1){
						nullRemoved = StringUtils.replace(nullRemoved,"(","|lbr|");
					}
					if(nullRemoved.indexOf(")") > -1){
						nullRemoved = StringUtils.replace(nullRemoved,")","|rbr|");
					}
				}
				JSONArray leftEntrs = new JSONArray();
				List duplicateChkList = new ArrayList();
				for (int l=0; l<left.length; l++)
				{
					String agentNameLower = left[l].toString().toLowerCase();
					if (duplicateChkList.contains(agentNameLower))
					{
						continue;
					}
					duplicateChkList.add(agentNameLower);

					JSONObject tmpObj = new JSONObject();
					String leftElStr = (String)left[l];
					if(leftElStr.indexOf("(") > -1){
						//leftElStr = leftElStr.replaceAll("\\(","|lbr|");
						leftElStr = StringUtils.replace(leftElStr,"(","|lbr|");
					}
					if(leftElStr.indexOf(")") > -1){
						//leftElStr = leftElStr.replaceAll("\\)","|rbr|");
						leftElStr = StringUtils.replace(leftElStr,")","|rbr|");
					}
					tmpObj.put("displayField",left[l]);
					tmpObj.put("valueField",left[l]);
					leftEntrs.add(tmpObj);
				}

				rootJSON.put("leftEntries",leftEntrs);
				rootJSON.put("leftSelected",nullRemoved);

				for(int i=0;i<leftAgents.size();i++){
					String leftAgentStr = ((String)leftAgents.get(i)).toString();
					if(leftAgentStr.indexOf("(") > -1){
						leftAgentStr = StringUtils.replace(leftAgentStr,"(","|lbr|");
					}
					if(leftAgentStr.indexOf(")") > -1){
						leftAgentStr = StringUtils.replace(leftAgentStr,")","|rbr|");
					}
					alreadyEnabledAgents += leftAgentStr+",";
				}
				if(alreadyEnabledAgents.indexOf(",")!=-1)
				{
					alreadyEnabledAgents = alreadyEnabledAgents.substring(0,alreadyEnabledAgents.lastIndexOf(","));
				}
			}

			rootJSON.put("rightSelectionTitle",_mapping.getTextDescription("admin.upgrade."+s_right_title));

			if (right.length > 0)
			{
				/* when we get version null we remove the null */
				String nullRemoved = (String)right[0];
				if(nullRemoved != null && nullRemoved.indexOf("(") !=-1)
				{
					String nullStr = nullRemoved.substring(nullRemoved.indexOf("(")+1,nullRemoved.indexOf(")"));
					if(nullStr !=null && nullStr.equalsIgnoreCase("null"))
						nullRemoved = nullRemoved.substring(nullRemoved.indexOf("("));

					if(nullRemoved.indexOf("(") > -1){
						nullRemoved = StringUtils.replace(nullRemoved,"(","|lbr|");
					}
					if(nullRemoved.indexOf(")") > -1){
						nullRemoved = StringUtils.replace(nullRemoved,")","|rbr|");
					}
				}
				//out.println(HtmlUtils.setSelectOptions(right, right[0]));
				//out.println(HtmlUtils.setSelectOptions(right, nullRemoved));

				JSONArray rightEntrs = new JSONArray();
				List duplicateChkList = new ArrayList();
				for (int l=0; l<right.length; l++)
				{
					String agentNameLower = right[l].toString().toLowerCase();
					if (duplicateChkList.contains(agentNameLower))
					{
						continue;
					}
					duplicateChkList.add(agentNameLower);

					JSONObject tmpObj = new JSONObject();
					String rigthElStr = (String)right[l];
					if(rigthElStr.indexOf("(") > -1){
						rigthElStr = StringUtils.replace(rigthElStr,"(","|lbr|");
					}
					if(rigthElStr.indexOf(")") > -1){
						rigthElStr = StringUtils.replace(rigthElStr,")","|rbr|");
					}
					tmpObj.put("displayField",right[l]);
					tmpObj.put("valueField",rigthElStr);
					rightEntrs.add(tmpObj);
				}
				rootJSON.put("rightEntries",rightEntrs);
				rootJSON.put("rightSelected",nullRemoved);
			}
		}
	}

	if(optionvalue !=null && optionvalue.equalsIgnoreCase("interval"))
	{
		String valFromIni = ini_read.getValue("AGENT_SETTINGS","AutoUpgradeInterval");
		try
		{
			old_interval = getIntervalWithUnits(Integer.parseInt(valFromIni));
		}
		catch(Exception e)
		{
			old_interval = "1 hr";
		}
		String unit = new String();
		int k=0;

		JSONArray times = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.upgrade.Choose an interval"));
		obj.put("valueField","0");
		times.add(obj);

		for(int i=0;i<19;i+=6)
		{
			if(i==0)
			{
				i=1;
				unit=" " + _mapping.getTextDescription("admin.upgrade.hr");
			}
			else
			{
				unit=" "+ _mapping.getTextDescription("admin.upgrade.hrs");
			}

			k= i * 12;
			if(k==Integer.parseInt(valFromIni) )
			{
				rootJSON.put("selectedInterval",k);
			}
			obj = new JSONObject();
			obj.put("displayField",(i+unit));
			obj.put("valueField",k);
			times.add(obj);
			if(i==1)
			{
				i=0;
			}
		}
		for (int y=1;y<7;y++)
		{
			if(y==1)
				unit=" "+_mapping.getTextDescription("admin.upgrade.day");
			else
				unit=" "+_mapping.getTextDescription("admin.upgrade.days");
			k=y*12*24;
			if(k==Integer.parseInt(valFromIni) )
			{
				rootJSON.put("selectedInterval",k);
			}
			obj = new JSONObject();
			obj.put("displayField",(y+unit));
			obj.put("valueField",k);
			times.add(obj);
		}

		k=2016;
		if(k==Integer.parseInt(valFromIni) )
		{
			rootJSON.put("selectedInterval",k);
		}
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.upgrade.1 week"));
		obj.put("valueField",k);
		times.add(obj);

		rootJSON.put("timeIntervals",times);
%>
<%
		JSONArray upgrade = new JSONArray();
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.upgrade.Enabled"));
		obj.put("valueField","Yes");
		upgrade.add(obj);
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.upgrade.Disabled"));
		obj.put("valueField","No");
		upgrade.add(obj);
		rootJSON.put("upgradeModes",upgrade);
		rootJSON.put("selectedUpgradeMode",defaultUpgradeValue);
	}
	//hiddens.put("fmanage","");
	//hiddens.put("funmanage","");
	hiddens.put("old_interval",old_interval);
	hiddens.put("alreadyEnabledAgents",alreadyEnabledAgents);
	//hiddens.put("managed_components","");
	rootJSON.put("hiddenVals",hiddens);

	out.println(rootJSON);
%>
<%!
	String getIntervalWithUnits(int interval)
	{
		if(interval<=216)
		{
			int tmp = interval/12;
			return ""+ tmp + (tmp==1? " hr":" hrs");
		}
		else if(interval<=1728)
		{
			int tmp = interval/288;
			return ""+ tmp + (tmp==1? " day":" days");
		}
		else //if(interval<=2016)
		{
			return "1 week";
		}
	}
	boolean isItemExists(ArrayList searchList, String server)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if (server.indexOf(nextStr)!= -1 || (server.toUpperCase().indexOf(nextStr.toUpperCase())) != -1)
			{
				return true;
			}
		}
		return false;
	}
%>
<%
if(request.getQueryString()!=null)
session.setAttribute("adminLastAccessedURL","/final/admin/EgManageAgents.jsp?"+request.getQueryString());
else session.setAttribute("adminLastAccessedURL","/final/admin/EgManageAgents.jsp");
%>
