#!/bin/env python
# -*- coding: utf-8 -*-
#
# By Igor V. Gubenko (igubenko@Princeton.EDU)
# 08/11/2017
#
#
#
#

import 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')

from pprint import pprint
import json, logging, os, re, requests, time
from xml.dom import minidom
from lxml import html

def outputheaders (reqst):
	print
	print "#### Headers:"
	print

	hdrs = reqst.headers
	for hdr in hdrs.keys():
		print "%s => %s" % (hdr, hdrs[hdr])

	print
	print "#### End headers"

def outputtext (reqst, ttype):
	print
	print "#### Text:"
	print
	print ttype
	print
	outp = ""
	obj = ""

	if re.match ('^application/json$', ttype):
		obj = reqst.json()
		outp = json.dumps (obj)
	elif re.match ('^application/xml$', ttype):
		obj = minidom.parseString (reqst.text)
		outp = obj.toprettyxml()
	else:
		outp = reqst.text

	print (outp)
	print
	print "#### End text"

url = "https://wase.Princeton.EDU"
statstr = "OK: Successfully retrieved %s, submitted a form, and located \"serge\"" % url
stat = 0

starttm = time.time()

try:
	req = requests.get (url)
except requests.exceptions.RequestException as excep:
	print "ERROR: Unable to resolve or connect to %s. Error received: %s" % (url, excep)
	sys.exit (2)

iniurltm = time.time()
initime = iniurltm - starttm

if req.status_code != 200:
	print "ERROR: We connected to %s, but the web server has returned error code %d" % (url, req.status_code)
	sys.exit(2)

#outputheaders (req)
#outputtext (req, req.headers['content-type'])

if initime >= 3:
	statstr = "WARNING: Getting initial page %s took %d seconds!" % (url, initime)
	stat = 1

try:
	## (We need to use page.content rather than page.text because html.fromstring implicitly expects bytes as input.)
	htmldom = html.fromstring (req.content)
	txtEmail = htmldom.xpath ('//input[@name="txtEmail"]')
except:
	pass

if not txtEmail or len(txtEmail) == 0:
	print "ERROR: Page %s possibly loaded incompletely, or changed. Unable to locate the email input box" % url
	sys.exit(2)

urlnew = req.url

try:
	req = requests.post (urlnew, data = {'btnLogInGuest': 'Guest+Log+In', 'txtEmail': 'serge secret=7eizje8zn'})
except requests.exceptions.RequestException as excep:
	print "ERROR: Unable to resolve or connect to %s. Error received: %s" % (urlnew, excep)
	sys.exit (2)

#outputheaders (req)
#outputtext (req, req.headers['content-type'])
#try:
#	print req.content
#except:
#	pass

endtm = time.time()
submtime = endtm - iniurltm

if req.status_code != 200:
	print "ERROR: We posted to %s, but the web server has returned error code %d" % (urlnew, req.status_code)
	sys.exit(2)

if submtime >= 3:
	statstr = "WARNING: Submit (POST) to page %s took %d seconds!" % (urlnew, submtime)
	stat = 1

try:
	## (We need to use page.content rather than page.text because html.fromstring implicitly expects bytes as input.)
	htmldom = html.fromstring (req.content)
	usermenu = htmldom.xpath ('//div[@id="usermenu"]')[0]
except:
	pass

if not re.search ('serge.*Log\sout', usermenu.text_content()):
	print "ERROR: Unable to locate \"Log out\" link for \"serge\" after POST";
	sys.exit(2)

print "%s | 'time_ini'=%.3fs;;; 'time_post'=%.3fs;;; 'total'=%.3fs;;;" % (statstr, initime, submtime, endtm - starttm)

sys.exit(stat)

