#!/usr/bin/python2

# ----------------------------------------------------------------------
# SSLCAUDIT - a tool for automating security audit of SSL clients
# Released under terms of GPLv3, see COPYING.TXT
# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
# ----------------------------------------------------------------------
# Code handling keyboard interrupts contributed by Raf Somers (raf.somers@telenet.be)
# ----------------------------------------------------------------------


import os, sys, logging

# if the script is launched from sources, make sure it uses modules located in the
# same place
base_dir = os.path.join(os.path.dirname(__file__), '..')
src_dir = os.path.join(base_dir, 'sslcaudit')
if os.path.exists(src_dir): sys.path.insert(0, base_dir)

from sslcaudit.core.ConfigError import ConfigError
from sslcaudit.core.FileBag import FileBag


def check_dependencies():
    # make sure M2Crypto is installed
    try:
        import M2Crypto

        return True
    except ImportError as ex:
        print 'Failed to load M2Crypto: %s' % ex
        print
        print 'Sslcaudit requires M2Crypto library. Please install your OS package or see'
        print 'website http://chandlerproject.org/bin/view/Projects/MeTooCrypto.'
        return False


def check_gui_dependencies():
    # make sure PyQT4 is installed
    try:
        import PyQt4

        return True
    except ImportError as ex:
        print 'Failed to load PyQT4: %s' % ex
        print
        print 'Sslcaudit GUI requires PyQT4 library. Please install your OS package.'
        return False


def init_logging(options, file_bag):
    FORMAT = '%(asctime)s %(name)s %(levelname)s   %(message)s'
    formatter = logging.Formatter(FORMAT)

    debugLogFile = file_bag.mk_filename(suffix='.log')
    debugLogFileHandler = logging.FileHandler(filename=debugLogFile)
    debugLogFileHandler.setLevel(logging.DEBUG)
    debugLogFileHandler.setFormatter(formatter)
    logging.getLogger().addHandler(debugLogFileHandler)

    consoleLogger = logging.StreamHandler()
    if options.debug_level > 0:
        # debugging
        consoleLogger.setLevel(logging.DEBUG)
    elif options.quiet:
        # quiet mode of operation, display warnings and errors only
        consoleLogger.setLevel(logging.WARN)
    else:
        # normal, reasonalby verbose mode of operation
        consoleLogger.setLevel(logging.INFO)
    consoleLogger.setFormatter(formatter)
    logging.getLogger().addHandler(consoleLogger)
    logging.getLogger().debug(
        'logging initialized, debug_level=%d, verbose=%s' % (options.debug_level, str(options.quiet)))
    logging.getLogger().setLevel(logging.DEBUG)


def main(argv):
    if not check_dependencies():
        return 1

    try:
        from sslcaudit.ui import SSLCAuditUI

        options = SSLCAuditUI.parse_options(argv[1:])
        if options.gui and not check_gui_dependencies():
            return 1

        file_bag = FileBag(options.test_name)

        init_logging(options, file_bag)

        if options.gui:
            from sslcaudit.ui.SSLCAuditGUI import SSLCAuditGUI

            ui = SSLCAuditGUI(options, file_bag)
        else:
            from sslcaudit.ui.SSLCAuditCLI import SSLCAuditCLI

            ui = SSLCAuditCLI(options, file_bag)

        return ui.run()
    except KeyboardInterrupt as ex:
        print 'Got KeyboardInterrupt exception before controller loop started, exiting'
        return 1
    except ConfigError as ex:
        print 'Configuration error: %s' % ex
        return 1
    except RuntimeError as ex:
        print 'Runtime error: %s' % ex
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

