#
# A script to reload the SSL certificates of vCenter via the MOB browser
# interface.
#
# This script tries to login to https://localhost/mob using HTTP Basic
# Authentication.
#

import sys
import getopt
import re
import urllib
import urllib2
from urllib2 import URLError, HTTPError
import signal

def signal_handler(signal, frame):
   print "Task Interrupted. Aborting..."
   sys.exit(1)

def Usage(msg="Unknown error"):
   print "Error: " + msg
   print("Usage: python reloadCerts.py -u <username> -p <password> -d <true|false>")
   sys.exit(1)

def main():
   # this url is a constant.
   url = "https://localhost/mob/?moid=vpxd-securitymanager&method=reloadSslCertificate&vmodl=1"

   try:

      opts,args = getopt.getopt(sys.argv[1:], "u:p:d:")

   except getopt.GetoptError:
      Usage("unknown argument(s)")

   if len(sys.argv) != 7:
      Usage("incorrect number of arguments")

   for a,v in opts:
      if a =="-u":
         username = v
      if a == "-p":
         password = v
      if a == "-d":
         dryrun = v

   try:

     passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
     passman.add_password(None,url,username,password)

     authhandler = urllib2.HTTPBasicAuthHandler(passman)
     proxyhandler = urllib2.ProxyHandler({}) #no proxy

     opener = urllib2.build_opener(proxyhandler, authhandler)

     urllib2.install_opener(opener)

   except HTTPError, e:
      print "HTTPError: Cannot build opener."
      print str(e)
      sys.exit(1)
   except URLError, e:
      print "URLError: Cannot build opener."
      print e
      sys.exit(1)
   except IOError, e:
      print "IOError: Cannot build opener."
      print e
      print e.errno
      sys.exit(1)

   try:

     request = urllib2.Request(url)
     page = urllib2.urlopen(request)
     pageContent = page.read()

   except HTTPError, e:
      print "HTTPError: Unable to open or read page."
      print str(e)
      sys.exit(1)
   except URLError, e:
      print "URLError: Unable to open or read page."
      print e
      sys.exit(1)
   except IOError, e:
      print "IOError: Unable to open or read page."
      print e
      print e.errno
      sys.exit(1)

   if dryrun == "true":
      print "Successfully logged in to vCenter Server"
      sys.exit(0)

   # the POST data requires vmware-session-nonce as input
   # otherwise, we get a "403: Forbidden: Possible Cross-Site Request Forgery"
   # error.
   regex = re.compile('name="vmware-session-nonce" type="hidden" value="?([^\s^"]+)"')
   nonce = regex.search(pageContent).group(1)

   # cache the cookie for later use
   headers = page.info()
   cookie = headers.get("Set-Cookie")

   try:

     params = {'vmware-session-nonce':nonce}
     data = urllib.urlencode(params)
     request = urllib2.Request(url, data, headers={"Cookie":cookie})
     page = urllib2.urlopen(request).read()

   except HTTPError, e:
      print "HTTPError: Unable to reload SSL Certificates."
      print str(e)
      sys.exit(1)
   except URLError, e:
      print "URLError: Unable to reload SSL Certificates."
      print e
      sys.exit(1)
   except IOError, e:
      print "IOError: Unable to reload SSL Certificates."
      print e
      print e.errno
      sys.exit(1)

   regex = re.compile('Method Invocation Result: void')
   reloaded = regex.search(page)

   if reloaded:
      # Success
      print "Successfully reloaded vCenter SSL Certificates"
      sys.exit(0)
   else:
      print "Could not reload vCenter SSL Certificates"
      sys.exit(1)

if __name__ == "__main__":
   #catch ctrl-c
   signal.signal(signal.SIGINT, signal_handler)
   try:
      main()
   except KeyboardInterrupt, e:
      print "Task Interrupted. Aborting..."
      sys.exit(1)

