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

import calendar, re, time, sys
sys.path.insert (1, '/usr/local/monitoring/princeton/lib')
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.support import expected_conditions as EC
from selenium.common import exceptions as EXCEP
from random import sample

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, fp = init_selenium(['mon200w', 'mon201w', 'mon202w', 'mon203w'])
#ff, fp = init_selenium(['mon203w'])
#ff, fp = init_selenium(['monitor'])
ff, fp = init_selenium()

try:
	#ff.implicitly_wait (10)

	try:
		ff.get (url)
		WebDriverWait (ff, 10).until (EC.presence_of_element_located((By.ID, "loginlink")))
		ff.find_element_by_xpath ("//img[@alt='Login']").click()
	except:
		print "Error retrieving the initial Webspace page, containing the login link"
		sys.exit (2)

	try:
		WebDriverWait (ff, 10).until (EC.title_contains("Princeton University Authentication Service"))

		WebDriverWait (ff, 10).until (EC.presence_of_element_located((By.NAME, "submit")))

		uid = ff.find_element_by_id ("username")
		uid.send_keys (usr)

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

		submt = ff.find_element_by_name ("submit").click()

	except:
		print "Error loading the CAS login page"
		sys.exit (2)

	try:
		WebDriverWait (ff, 10).until (EC.title_contains("Xythos - Document Manager"))
		ff.find_element_by_xpath ("//a[text()='[Logout]']").click()

		try:
			WebDriverWait (ff, 10).until (EC.title_contains("WebSpace Logout"))
			ff.find_element_by_xpath ("//img[@alt='CAS Logout']").click()
		except:
			print "Successfully logged in, but couldn't log out"
			sys.exit (1)
	except:
		#print "#%s#\n#%s#\n" % (url, ff.current_url)
		if not re.match ("^https://webspace", url) and re.match ("^https://webspace", ff.current_url) and ff.find_element_by_xpath ("//img[@alt='Login']") and re.match ("^.*Welcome to WebSpace", ff.page_source):
			pass
		else:
			print "Failed logging in to Webspace or the page didn't fully load"
			sys.exit (2)

	time.sleep(1)

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

except EXCEP.NoSuchElementException, msg:

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

except EXCEP.TimeoutException, msg:

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

except EXCEP.WebDriverException, msg:

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

finally:
	ff.quit()

print "Successfully logged on to Webspace and logged off"

sys.exit (0)

