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

import calendar, 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 ()

try:
	start_url = time.time()
	ff.implicitly_wait (10)

	try:
		ff.get (url)
	except:
		print "Unable to retrieve URL \"%s\"" % url
		sys.exit(2)

	start_login = time.time()

	try:
		uid = ff.find_element_by_id ("username")
		uid.send_keys (usr)
	
		pupass = ff.find_element_by_id ("password")
		pupass.send_keys (usrpass)
		pupass.submit()
	except:
		print "Error navigating the CAS login page."
		sys.exit(2)

	try:
		WebDriverWait (ff, 10).until (EC.title_contains("Welcome to IBM Cognos software"))

		login_time = time.time()

		ff.find_element_by_link_text ("Log Off").click()
	except:
		print "Error logging in or retrieving the Cognos webpage"
		sys.exit(2)

	logout_time = time.time()
	try:
		ff.find_element_by_name ("logout-button").click()

		WebDriverWait (ff, 10).until (EC.title_contains("Princeton University Logout Page"))

	except:
		print "Error logging out or retrieving the CAS logout page"
		
		end_time = time.time()

		sys.exit(1)
       
	end_time = time.time()

	time.sleep(5)

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

print "Successfully logged on to IW/Cognos and logged off | 'loginpage_get'=%.2fs;;; 'fulllogin'=%.2fs;;; 'logout'=%.2fs;;; 'cas_logout'=%.2fs;;; 'total'=%.2fs;;;" % ((start_login - start_url), (login_time - start_login), (logout_time - login_time), (end_time - logout_time), (end_time - start_url))

sys.exit (0)
