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

import calendar, time, sys
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.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common import exceptions as EXCEP

if len (sys.argv) != 4:
	print "Usage: %s <URL> <username> <password>" % sys.argv[0]
	sys.exit (3)

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

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

try:
	ff.implicitly_wait (30)
	#ff.allowNativeXpath("false")

	try:
		ff.get (url)

		WebDriverWait (ff, 10).until (EC.title_contains("WorkPlace"))

		rid = Select (ff.find_element_by_id ("realmID"))
		rid.select_by_visible_text ("Princeton University")

		ff.find_element_by_name ("realmButton").submit()
	except:
		print "Error accessing the initial SRA realm selection page"
		sys.exit (2)

	#try:
	#	ff.get (url)

	#	WebDriverWait (ff, 10).until (EC.title_contains("Secure Remote Access"))
	#except:
	#	print "Error accessing the SRA login page"
	#	sys.exit (2)

	try:
		WebDriverWait (ff, 10).until (EC.presence_of_element_located((By.ID, "data_0")))

		puusr = ff.find_element_by_id ("data_0")
		puusr.send_keys (usr)

		pupass = ff.find_element_by_id ("data_1")
		pupass.send_keys (usrpass)

		ff.find_element_by_name ("okButton").click()
	except:
		print "Error accessing elements on the SRA login page"
		sys.exit (2)
		

	# look for "Session Limit", and if so, press OK
	try:
		#print "Look for Session Limit"
		WebDriverWait (ff, 10).until (EC.text_to_be_present_in_element((By.TAG_NAME, "b"), 'Session Limit'))
		#if not ff.find_element_by_xpath ("//div[contains(.,'Session Limit')]"):
		#	raise
		#print "Session Limit found"
		ff.find_element_by_name ("okButton").click()
		#print "Clicked on OK"
	except:
		pass

	# Look for "Missing Components", and if so, press "Continue"
	try:
		#print "Look for Missing Components"
		WebDriverWait (ff, 10).until (EC.text_to_be_present_in_element((By.TAG_NAME, "body"), 'Missing Components'))
		#if not ff.find_element_by_xpath ("//body[contains(.,'Missing Components')]"):
		#	raise
		#print "Missing Components found"
		#ff.find_element_by_xpath ("//input[@type='button'][@value=' Continue ']").click()
		ff.find_element_by_css_selector ("input.submitbutton[value*='Continue']").click()
		#print "Clicked on Continue"

	except:
		# Look for "Aventail Access Manager", and if so, press Remind Me Later
		try:
			#print "Look for Aventail Access Manager"
			WebDriverWait (ff, 10).until (EC.text_to_be_present_in_element((By.TAG_NAME, "div"), 'Aventail Access Manager'))
			#if not ff.find_element_by_xpath ("//div[contains(.,'Aventail Access Manager')]"):
			#	raise
			#print "Aventail Access Manager found"
			ff.find_element_by_xpath ("//input[@type='button'][@value=' Remind me later ']").click()
			#ff.execute_script ("setEPCCookie('remind_me_later', 'true', false); document.location='/postauth/__EPCinterrogatornext?success=%2Fworkplace%2Faccess%2Fhome';")
			#print "Clicked on Remind Me Later"

		except:
			pass

	# Check if we are in fact logged in to the main site. If so, log out
	try:
		WebDriverWait (ff, 30).until (EC.presence_of_element_located((By.XPATH, "//a[@title='Log out']")))
		ff.find_element_by_xpath ("//a[@title='Log out']").click()
	except:
		#print "Unable to locate known webpage elements, such as \"Remind Me Later\" button, \"Missing Components\" dialog, or \"Log out\" link. Maybe the page loaded incorrectly"
		print "Unable to locate known webpage elements after login, such as the \"Log out\" link. Maybe the page loaded incorrectly"
		sys.exit (2)

	exit_stat = 0
	# Check if we logged out successfully
	try:
		WebDriverWait (ff, 10).until (EC.text_to_be_present_in_element((By.TAG_NAME, "body"), 'Logout successful'))

		print "Successfully logged on to %s and logged out" %url
	except:
		print "Successfully logged on to %s but failed to log out" %url
		exit_stat = 1

	time.sleep(3)

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. 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 (exit_stat)
