#!/usr/local/monitoring/bin/python

import calendar, time, sys, re, os
sys.path.insert (1, '/usr/local/monitoring/princeton/lib')
#sys.path.insert (2, '/usr/local/monitoring/python/lib/python2.7/site-packages')
#sys.path.insert (3, '/usr/local/monitoring/python/lib/python2.7')
#sys.path.insert (4, '/usr/local/monitoring/python/lib64/python2.6/site-packages')
#sys.path.insert (5, '/usr/local/monitoring/python/lib/python2.6/site-packages')  
#sys.path.insert (6, '/usr/local/monitoring/python/lib/python2.6/site-packages/selenium-2.48.0-py2.6.egg')
from puselenium import init_selenium

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.common import exceptions as EXCEP
from random import sample, randrange

verb = 0

def tm (tmconv):
	return time.strftime("%D %H:%M:%S", time.localtime(tmconv))

def outp (str, level = 1):
	if verb >= level:
		print "%d: %s" % (level, str)
	#print "%d %d" % (verb, level)

def usage ():
	print "Usage: %s <ClearPass host or URL to test> <username> <password> [verbosity=1] [alloted_run_time=180]" % sys.argv[0]
	sys.exit (3)

if len (sys.argv) < 4:
	usage

url = sys.argv[1]
usr = sys.argv[2]
usrpass = sys.argv[3]
atime = 180

if len (sys.argv) > 4:
	verb = int (sys.argv[4])
if len (sys.argv) > 5:
	atime = int (sys.argv[5])

outp ("%s: Starting program" % tm(time.time()), 2)

#ff = puselenium.init_selenium (['ims316', 'ims317', 'mon200w', 'mon201w', 'mon202w', 'mon203w'])
ff, fp = init_selenium ()

try:
	### Load initial URL
	t_ini = time.time()
	outp ("%s: Loaded browser" % tm(t_ini), 2)
	#ff.implicitly_wait (10)

	main_window = ff.current_window_handle

	outp ("Retrieving URL %s" % url, 1)
	ff.get (url)
	#ff.allowNativeXpath("false");

	### Check for the sign on page to enter the username
	#try:
	#	WebDriverWait (ff, 60).until (EC.title_contains("ClearPass Policy Manager"))
	#except:
	#	outp ("Unable to reach the initial ClearPass page", 0)
	#	sys.exit (2)

	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.XPATH, "//a[contains(.,'ClearPass Guest')]")))

		t_main = time.time()
		outp ("%s: ClearPass initial page retrieved" % tm(t_main), 2)
		outp ("Clicking on ClearPass Guest", 1)
		ff.find_element_by_xpath ("//a[contains(.,'ClearPass Guest')]").click()

	except:
		outp ("Unable to locate the ClearPass Guest link", 0)
		sys.exit (2)

	time.sleep(2)
	for win in ff.window_handles:
		ff.switch_to.window (win)
		#outp ("Found Window %s" % ff.current_url, 0)
		if re.match ("/guest/(guest_index.php|auth_login.php)", ff.current_url, flags=re.IGNORECASE):
			break
		win = False
	ff.maximize_window()

	#next_window = ff.window_handles[-1]
	#ff.switch_to.window (next_window)

	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.ID, "ID_form4da79e65_auth_login_username")))

		t_login_cpguest = time.time()
		outp ("%s: ClearPass Guest Login page retrieved" % tm(t_login_cpguest), 2)
		outp ("Entering login fields and clicking on \"Log In\"", 1)

		uidfield = ff.find_element_by_id ("ID_form4da79e65_auth_login_username")
		uidfield.send_keys (usr)
		passfield = ff.find_element_by_id ("ID_form4da79e65_auth_login_password")
		passfield.send_keys (usrpass)

		passfield.submit()

	except:
		outp ("Unable to locate one or more fields on the ClearPass Guest Login page. Maybe the page didn't load or change?", 0)
		sys.exit (2)


	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.XPATH, "//a[contains(.,'Manage Devices')]")))

		t_cpguest_console = time.time()
		outp ("%s: ClearPass Guest Portal page retrieved" % tm(t_cpguest_console), 2)
		outp ("Clicking on \"Manage Devices\"", 1)
		ff.find_element_by_xpath ("//a[contains(.,'Manage Devices')]").click()
	except:
		outp ("Unable to login to the ClearPass Guest portal or the page loads incompletely", 0)
		sys.exit (2)


	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.ID, "mac_list_item_20")))

		t_cpguest_devices = time.time()
		outp ("%s: Loaded devices" % tm(t_cpguest_devices), 2)
		outp ("Logging out from ClearPass Guest", 1)
		ff.find_element_by_xpath ("//a[contains(.,'Logout')]").click()
	except:
		outp ("Unable to locate the 20th (last) device on the page. There might be a problem loading the device page", 0)
		sys.exit (2)

	WebDriverWait (ff, 60).until (EC.title_contains("Login"))
	ff.close()
	ff.switch_to.window (main_window)


	try:
		t_cpguest_logout = time.time()
		outp ("%s: Logged out from ClearPass Guest and ready to go into ClearPass Policy Manager" % tm(t_cpguest_logout), 2)
		outp ("Clicking on ClearPass Policy Manager", 1)
		ff.find_element_by_xpath ("//a[contains(.,'ClearPass Policy Manager')]").click()

	except:
		outp ("Unable to locate the ClearPass Policy Manager link. This is weird and shouldn't have happened.", 0)
		sys.exit (2)

	time.sleep(2)
	for win in ff.window_handles:
		ff.switch_to.window (win)
		#outp ("Found Window %s" % ff.current_url, 0)
		if re.match ("/tips/tipsLogin.action", ff.current_url, flags=re.IGNORECASE):
			break
		win = False
	ff.maximize_window()

	#next_window = ff.window_handles[-1]
	#ff.switch_to.window (next_window)

	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.NAME, "password")))

		t_login_cppm = time.time()
		outp ("%s: ClearPass Policy Manager Login page retrieved" % tm(t_login_cppm), 2)
		outp ("Entering login fields and clicking on \"Log In\"", 1)

		uidfield = ff.find_element_by_id ("username")
		uidfield.send_keys (usr)
		passfield = ff.find_element_by_name ("password")
		passfield.send_keys (usrpass)

		passfield.submit()

	except:
		outp ("Unable to locate one or more fields on the ClearPass Policy Manager Login page. Maybe the page didn't load or change?", 0)
		sys.exit (2)


	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.ID, "menu_5_5_button")))

		t_cppm_console = time.time()
		outp ("%s: ClearPass Policy Manager Portal page retrieved" % tm(t_cppm_console), 2)
		outp ("Clicking on \"Conguration\" section", 1)
		ff.find_element_by_id ("menu_5_5_button").click()
	except:
		outp ("Unable to login to the ClearPass Policy Manager portal or the page loads incompletely", 0)
		sys.exit (2)



	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.XPATH, "//span[contains(.,'Network')]")))

		t_cppm_config = time.time()
		outp ("%s: Loaded the \"Configuration\" section" % tm(t_cppm_config), 2)
		outp ("Clicking on the \"Network\" menu", 1)
		ff.find_element_by_xpath ("//div[@id='menu_5_5']/div/div/div[2]/div[7]").click()
	except:
		outp ("Unable to click on the \"Network\" Menu. Maybe the page loaded incompletely", 0)
		sys.exit (2)


	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.XPATH, "//span[contains(.,'Devices')]")))

		t_cppm_network = time.time()
		outp ("%s: Loaded the \"Network\" menu" % tm(t_cppm_network), 2)
		outp ("Clicking on the \"Devices\" menu", 1)
		ff.find_element_by_xpath ("//span[contains(.,'Devices')]").click()
	except:
		outp ("Unable to click on the \"Devices\" Menu. Maybe the page loaded incompletely", 0)

	try:
		WebDriverWait (ff, 60).until (EC.presence_of_element_located((By.XPATH, "//span[contains(.,'Aruba Controllers')]")))

		t_cppm_devices = time.time()
		outp ("%s: Loaded the \"Devices\" section" % tm(t_cppm_devices), 2)
		outp ("Logging out from ClearPass Policy Manager", 1)
		ff.find_element_by_xpath ("//a[contains(.,'Logout')]").click()
	except:
		outp ("Unable to locate the 20th (last) device on the page. There might be a problem loading the device page", 0)
		sys.exit (2)

	WebDriverWait (ff, 60).until (EC.title_contains("ClearPass Policy Manager"))
	ff.close()
	ff.switch_to.window (main_window)

	msg_final = "Successfully tested ClearPass"
	t_end = time.time()

	outp ("%s | \
'main_page'=%.3fs;;; \
'guest_login'=%.3fs;;; \
'guest_console'=%.3fs;;; \
'guest_devices'=%.3fs;;; \
'guest_logout'=%.3fs;;; \
'cppm_login'=%.3fs;;; \
'cppm_console'=%.3fs;;; \
'cppm_config'=%.3fs;;; \
'cppm_network'=%.3fs;;; \
'cppm_devices'=%.3fs;;; \
'total_run'=%.3fs;;;" \
	% \
	(msg_final, \
	(t_main - t_ini),\
	(t_login_cpguest - t_main),\
	(t_cpguest_console - t_login_cpguest),\
	(t_cpguest_devices - t_cpguest_console),\
	(t_cpguest_logout - t_cpguest_devices),\
	(t_login_cppm - t_cpguest_logout),\
	(t_cppm_console - t_login_cppm),\
	(t_cppm_config - t_cppm_console),\
	(t_cppm_network - t_cppm_config),\
	(t_cppm_devices - t_cppm_network),\
	(t_end - t_ini)), 0)

	time.sleep(2)

except EXCEP.ErrorInResponseException, (resp, msg):
	
	print "ERROR: An error occured communicating with the browser server: Response: %s; Message: %s" % (resp, msg)
	sys.exit (2)

except EXCEP.NoSuchElementException, msg:

	print "ERROR: Unable to locate webpage element. Probably the page loaded incompletely or incorrectly: %s" % msg
	sys.exit (2)

except EXCEP.TimeoutException, msg:

	print "ERROR: Request timed out. Network??? Response: %s" % msg
	sys.exit (2)

except EXCEP.WebDriverException, msg:

	print "ERROR: I don't know what happened. Read this - %s" % msg
	sys.exit (2)

finally:
	ff.quit()

sys.exit (0)
