#!/usr/bin/python

import sys, re, pexpect
import Log

try:
	from Config import libPaths, dbName, dbUser, dbPass, dbHost, dbPort
except:
	Log.Message ("Error occured in finding basic configuration paramaters. Reverting to installer.", "index.py", "ERROR")
	import install
	sys.exit ()

for path in libPaths: sys.path.append (path)

try:
	import pycisco, pyaaa
except:
	Log.Message ("Couldn't import pycisco or pyaaa. Reverting to installer.", "index.py", "ERROR")
	import install
	sys.exit ()

import cgi, cgitb
cgitb.enable ()
print "Content-Type: text/html"
print
print """
<!--#set var="TITLE" value="Port Administration Configuration Tool" -->
<!--#set var="SIDEBAR" value="../sidebar.py" -->
<!--#include virtual="includes/header.html" -->
"""

print "<h2>Port Administration Configuration Tool</h2>"

form = cgi.FieldStorage ()


def ShowDefaultPage ():
	print "<p>Select a switch to get started!</p>"
	print "<form action='index.py' method='get'>"
	print "<select name='switch'>"
	for switch in switchList:
		print "<option value='" + switch + "'>" + switch + "</option>"
	print "</select>"
	print "<input type='hidden' name='action' value='status' />"
	print "<input type='submit' value='View Port Summary' />"
	print "</form>"

def ShowSwitchStatus (switchName):
	print "<h3>Port summary for " + switchName + "</h3>"
	
	print "<script type='text/javascript'>"
	print """
	$(document).ready (function () {
		$("a.portfast").click (function () {
			// Change the appearance and class so that it's no longer a "reveal"-style link
			$(this).attr ("class", "portfastload");
			$(this).text ("Wait...");
			
			portName = $(this).parents("tr").attr ('id');
			$(this).load ("update.py?action=getportfast&switch=""" + switchName + """&port=" + portName);
			$(this).unbind ();
			$(this).click (togglePortfast);
		});
		$("a.errors").click (function () {
			$(this).attr ("class", "errorsload");
			$(this).text ("Wait...");
			td = $(this).parents ("td");
			portName = $(this).parents("tr").attr ('id');
			td.load ("update.py?action=geterrors&switch=""" + switchName + """&port=" + portName);
		});
		$("a.status").click (function () {
			$(this).attr ("class", "statusload");
			$(this).text ("Wait...");
			td = $(this).parents ("td");
			portName = $(this).parents("tr").attr ('id');
			$(this).load ("update.py?action=toggleshutdown&switch=""" + switchName + """&port=" + portName);
		});
		togglePortfast = function () {
			$(this).text ("Wait...");
			portName = $(this).parents("tr").attr ('id');
			$(this).load ("update.py?action=toggleportfast&switch=""" + switchName + """&port=" + portName);
		};
		toggleShutdown = function () {
			$(this).text ("Wait...");
			portName = $(this).parents("tr").attr ('id');
			$(this).load ("update.py?action=toggleshutdown&switch=""" + switchName + """&port=" + portName);
		};
		descClick = function () {
			$(this).attr ("class", "descinput");
			portName = $(this).parents("tr").attr ('id');
			td = $(this).parents ("td");
			td.html ("<input type='text' value='" + $(this).text() + "' />");
			td.children ().focus ().blur (function () {
				portName = $(this).parents("tr").attr ('id');
				portDesc = $(this).attr ("value");
				td = $(this).parents ("td");
				td.html ("<a style='cursor:pointer'>Saving...</a>");
				td.children ().click (descClick);
				td.children().load ("update.py?action=setdescription&switch=""" + switchName + """&port=" + portName + "&desc=" + escape (portDesc));
			});
			//td.load ("update.py?action=geterrors&switch=""" + switchName + """&port=" + portName);
		};
		vlanClick = function () {
			$(this).attr ("class", "vlaninput");
			portName = $(this).parents("tr").attr ('id');
			td = $(this).parents ("td");
			td.html ("<input type='text' value='" + $(this).text() + "' />");
			td.children ().focus ().blur (function () {
				portName = $(this).parents("tr").attr ('id');
				vlan = $(this).attr ("value");
				td = $(this).parents ("td");
				td.html ("<a style='cursor:pointer'>Saving...</a>");
				td.children ().click (vlanClick);
				td.children().load ("update.py?action=setvlan&switch=""" + switchName + """&port=" + escape(portName) + "&vlan=" + escape (vlan));
			});
		};
		$("a.desc").click (descClick);
		$("a.vlan").click (vlanClick);
	});
	"""
	print "</script>"
	
	try:
		switch = pyaaa.SafeObject (pycisco.NetworkDevice (), switchName)
		switch._username = "me"
		switch._Remap ("Connect", {"hostname" : "hostname", "username" : "usern", "password" : "passw", "enable" : "enablepw"})
		switch.Connect ()
		ports = switch.GetPortSummary ()
	except pexpect.TIMEOUT:
		print "<h3 style='color:rgb(255,0,0)'>Switch appears to be down.</h3>"
		return
	print "<table border='0' cellpadding='2' cellspacing='0' class='rowset' >"
	print "<tr>"
	print "<th>Number</th>"
	print "<th>Description</th>"
	print "<th>Connected</th>"
	print "<th>VLAN</th>"
	print "<th>Duplex</th>"
	print "<th>Speed</th>"
	print "<th>Media</th>"
	print "<th>Portfast</th>"
	print "<th>Errors</th>"
	print "</tr>"
	even = True
	for port in ports:
		print "<tr class='" + (even and "even" or "odd") + "' id='" + port["name"] + "'>"
		print "<td>" + port["name"] + "</td>"
		print "<td><a style='cursor:pointer' class='desc'>" + (port["description"] or "(not set)") + "</a></td>"
		print "<td><a style='cursor:pointer' class='status'>" + port["connectstate"] + "</a></td>"
		print "<td><a style='cursor:pointer' class='vlan'>" + port["vlan"] + "</a></td>"
		print "<td>" + port["duplex"] + "</td>"
		print "<td>" + port["speed"] + "</td>"
		print "<td>" + port["media"] + "</td>"
		print "<td><a style='cursor:pointer' class='portfast'>" + port["portfast"] + "</a></td>"
		print "<td><a style='cursor:pointer' class='errors'>" + port["errors"] + "</td>"
		print "</tr>"
		even = not even
	print "</table>"


if not form.has_key ("action"):
	swInfo = pyaaa.SafeBase ()
	swInfo._username = "me"
	switchList = swInfo._GetRecords ("NetworkDevice")
	ShowDefaultPage ()
elif form["action"].value == "status":
	if not form.has_key ("switch"):
		print "Missing switch argument, please stop trying to craft your own URLs!"
	else:
		ShowSwitchStatus (form["switch"].value)

print """<!--#include virtual="includes/footer.html" -->"""
