#!/opt/vmware/bin/python
# -------------------------------------------------------------
# Copyright (C) 2012 VMware, Inc. All rights reserved. -- VMware Confidential
# -------------------------------------------------------------
#
# netdumper-webserver.py
#
# This is a very simple http server service which is used to by the netdumper
# plugin to serve up the page displaying netdumper current configuration, health
# and resource bundle
#

"""
 simple http server.
"""
import argparse
import logging
import logging.handlers
import os
import sys
import glob
import socket

# Add the source dir and all eggs there to the sys path
sourceDir = os.path.dirname(os.path.abspath('__file__'))
for egg in glob.glob('%s/*.egg' % sourceDir):
    sys.path.append(egg)
sys.path.append(sourceDir)

from webservice.webservice import NetdumpWebServerStart

configOptions = {}

logger = logging.getLogger('netdumper.webserver')

def CreateSyslogHandler(host=None, port=None):
    from com.vmware.cis.syslog import ClsSysLogHandler

    address = (str(host) if host else 'localhost',
               int(port) if port else logging.handlers.SYSLOG_UDP_PORT)

    handler = ClsSysLogHandler(identity='netdumper.webserver',
                               address=address)
    handler.socktype = socket.SOCK_DGRAM
    return handler

def CreateFileHandler(logFile):
    handler = logging.handlers.RotatingFileHandler(logFile,
                                                   maxBytes=1048576,
                                                   backupCount=10)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    return handler

def SetupWebServer():
    NetdumpWebServerStart(configOptions)

def ProcessOptions(args):
    parser = argparse.ArgumentParser(description="Parse command args")
    parser.add_argument('--verbose', help="run in verbose mode", action='store_true')
    parser.add_argument('--debug', help="run in debug mode", action='store_true')
    if os.name == 'posix':
        parser.add_argument('--configFile', help="path to configuration file",
                            type=file, default='/etc/sysconfig/netdumper')
    else:
        parser.add_argument('--configFile', help="path to configuration file",
                            type=file,
                            default=os.path.join(os.environ['VMWARE_DATA_DIR'],
                                                'netdump',
                                                'netdumper.sysconfig'))

    options = parser.parse_args(args)
    for line in options.configFile:
        setting = line.split('#')[0].strip()
        if setting:
            key, val = setting.split('=')
            configOptions[key] = val
    options.configFile.close()

    # Initialize logging
    if options.verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    if os.name == 'posix':
        logFile = configOptions.get('NETDUMPER_WEBSERVER_LOG_FILE')
        if logFile:
            logHandler = CreateFileHandler(logFile)
        else:
            try:
                logHandler = CreateSyslogHandler(configOptions.get('NETDUMPER_SYSLOG_HOST'),
                                                 configOptions.get('NETDUMPER_SYSLOG_PORT'))
            except ImportError:
                logHandler = CreateFileHandler('/var/log/vmware/netdumper/' + \
                                               'webserver.log')
    else:
        logFile = os.path.join(os.environ['VMWARE_LOG_DIR'],
                               'netdump', 'webserver.log')
        logHandler = CreateFileHandler(logFile)

    logger.addHandler(logHandler)
    logger.debug("Starting logging...")

    configOptions['extAddress'] = configOptions['NETDUMPER_HOST']
    configOptions['port'] = configOptions['NETDUMPER_PORT']
    configOptions['webPort'] = configOptions['NETDUMPER_WEBPORT']
    configOptions['vcThumbprint'] = ''
    if os.name == 'posix':
        resourcebundlePath = '/etc/vmware-netdump/resourceBundle.zip'
    else:
        resourcebundlePath = os.path.join(os.environ['VMWARE_DATA_DIR'],
                                         'netdump', 'resourceBundle.zip')
    configOptions['resbundlePath']= resourcebundlePath
    for key, val in configOptions.iteritems():
        if val:
            os.environ[key] = str(val)


def main(args):
    ProcessOptions(args[1:])
    SetupWebServer()
    return 0;


if __name__ == '__main__':
    logger.debug("Logging vmware-network-coredump-webserver init message..")
    sys.exit(main(sys.argv))
