# Path: applications/utils.py
# def mkdir_p(path):
#     """
#     Pythonic version of "mkdir -p".  Example equivalents::
# 
#         >>> mkdir_p('/tmp/test/testing') # Does the same thing as...
#         >>> from subprocess import call
#         >>> call('mkdir -p /tmp/test/testing')
# 
#     .. note:: This doesn't actually call any external commands.
#     """
#     try:
#         os.makedirs(path)
#     except OSError as exc:
#         if exc.errno == errno.EEXIST:
#             pass
#         else:
#             logging.error(_("Could not create directory: %s") % path)
#             raise # The original exception
# 
# Path: applications/utils.py
# def getsettings(name,default=None):
#     return getattr(settings, name, default)
# 
# def convert_to_timedelta(time_val):
#     """
#     Given a *time_val* (string) such as '5d', returns a `datetime.timedelta`
#     object representing the given value (e.g. `timedelta(days=5)`).  Accepts the
#     following '<num><char>' formats:
# 
#     =========   ============ =========================
#     Character   Meaning      Example
#     =========   ============ =========================
#     (none)      Milliseconds '500' -> 500 Milliseconds
#     s           Seconds      '60s' -> 60 Seconds
#     m           Minutes      '5m'  -> 5 Minutes
#     h           Hours        '24h' -> 24 Hours
#     d           Days         '7d'  -> 7 Days
#     M           Months       '2M'  -> 2 Months
#     y           Years        '10y' -> 10 Years
#     =========   ============ =========================
# 
#     Examples::
# 
#         >>> convert_to_timedelta('7d')
#         datetime.timedelta(7)
#         >>> convert_to_timedelta('24h')
#         datetime.timedelta(1)
#         >>> convert_to_timedelta('60m')
#         datetime.timedelta(0, 3600)
#         >>> convert_to_timedelta('120s')
#         datetime.timedelta(0, 120)
#     """
#     try:
#         num = int(time_val)
#         return timedelta(milliseconds=num)
#     except ValueError:
#         pass
#     num = int(time_val[:-1])
#     if time_val.endswith('s'):
#         return timedelta(seconds=num)
#     elif time_val.endswith('m'):
#         return timedelta(minutes=num)
#     elif time_val.endswith('h'):
#         return timedelta(hours=num)
#     elif time_val.endswith('d'):
#         return timedelta(days=num)
#     elif time_val.endswith('M'):
#         return timedelta(days=(num*30))  # Yeah this is approximate
#     elif time_val.endswith('y'):
#         return timedelta(days=(num*365)) # Sorry, no leap year support
# 
# def none_fix(val):
#     """
#     If *val* is a string that utlimately means 'none', return None.  Otherwise
#     return *val* as-is.  Examples::
# 
#         >>> none_fix('none')
#         None
#         >>> none_fix('0')
#         None
#         >>> none_fix('whatever')
#         'whatever'
#     """
#     if isinstance(val, basestring) and val.lower() in ['none', '0', 'no']:
#         return None
#     else:
#         return val
# 
# def gen_self_signed_ssl(path=None):
#     """
#     Generates a self-signed SSL certificate using `pyOpenSSL` or the
#     `openssl <http://www.openssl.org/docs/apps/openssl.html>`_ command
#     depending on what's available,  The resulting key/certificate will use the
#     RSA algorithm at 4096 bits.
#     """
#     try:
#         import OpenSSL
#         # Direct OpenSSL library calls are better than executing commands...
#         gen_self_signed_func = gen_self_signed_pyopenssl
#     except ImportError:
#         gen_self_signed_func = gen_self_signed_openssl
#     try:
#         gen_self_signed_func(path=path)
#     except SSLGenerationError as e:
#         logging.error(_(
#             "Error generating self-signed SSL key/certificate: %s" % e))


import os.path, sys, logging
import socket
    import simplejson as json
    import json
    import curses  # type: ignore
    import colorama
from applications.utils import mkdir_p
from applications.utils import getsettings,convert_to_timedelta,none_fix,gen_self_signed_ssl
from tornado import locale
    configure = False
    login_url ='/auth'
    static_url_prefix = '/static/'
    log_rotate_mode = 'size'
    logging = 'info'
    static_url = os.path.join(settings_base, 'static')
    session_logging = True
    log_file_num_backups = 10
    log_file_prefix = os.path.join(settings_base, 'log')
    if not os.path.exists(log_file_prefix):
        mkdir_p(log_file_prefix)
        os.chmod(log_file_prefix, 0o770)
    #if not check_write_permissions(uid, log_file_prefix):
        #recursive_chown(log_file_prefix, uid, gid)
    if not url_prefix.endswith('/'):
        url_prefix += '/' 
    global TIMEOUT
    TIMEOUT = convert_to_timedelta(session_timeout)
    api_timestamp_window = convert_to_timedelta(api_timestamp_window)
    auth = none_fix(auth)
    # Check to make sure we have a certificate and keyfile and generate fresh
    # ones if not.
    if not disable_ssl:
        if not os.path.exists(keyfile):
            ssl_base = os.path.dirname(keyfile)
            if not os.path.exists(ssl_base):
                mkdir_p(ssl_base)
            gen_self_signed_ssl(path=ssl_base)
        if not os.path.exists(certificate):
            ssl_base = os.path.dirname(certificate)

# Path: applications/utils.py
# def mkdir_p(path):
#     """
#     Pythonic version of "mkdir -p".  Example equivalents::
# 
#         >>> mkdir_p('/tmp/test/testing') # Does the same thing as...
#         >>> from subprocess import call
#         >>> call('mkdir -p /tmp/test/testing')
# 
#     .. note:: This doesn't actually call any external commands.
#     """
#     try:
#         os.makedirs(path)
#     except OSError as exc:
#         if exc.errno == errno.EEXIST:
#             pass
#         else:
#             logging.error(_("Could not create directory: %s") % path)
#             raise # The original exception
# 
# Path: applications/utils.py
# def getsettings(name,default=None):
#     return getattr(settings, name, default)
# 
# def convert_to_timedelta(time_val):
#     """
#     Given a *time_val* (string) such as '5d', returns a `datetime.timedelta`
#     object representing the given value (e.g. `timedelta(days=5)`).  Accepts the
#     following '<num><char>' formats:
# 
#     =========   ============ =========================
#     Character   Meaning      Example
#     =========   ============ =========================
#     (none)      Milliseconds '500' -> 500 Milliseconds
#     s           Seconds      '60s' -> 60 Seconds
#     m           Minutes      '5m'  -> 5 Minutes
#     h           Hours        '24h' -> 24 Hours
#     d           Days         '7d'  -> 7 Days
#     M           Months       '2M'  -> 2 Months
#     y           Years        '10y' -> 10 Years
#     =========   ============ =========================
# 
#     Examples::
# 
#         >>> convert_to_timedelta('7d')
#         datetime.timedelta(7)
#         >>> convert_to_timedelta('24h')
#         datetime.timedelta(1)
#         >>> convert_to_timedelta('60m')
#         datetime.timedelta(0, 3600)
#         >>> convert_to_timedelta('120s')
#         datetime.timedelta(0, 120)
#     """
#     try:
#         num = int(time_val)
#         return timedelta(milliseconds=num)
#     except ValueError:
#         pass
#     num = int(time_val[:-1])
#     if time_val.endswith('s'):
#         return timedelta(seconds=num)
#     elif time_val.endswith('m'):
#         return timedelta(minutes=num)
#     elif time_val.endswith('h'):
#         return timedelta(hours=num)
#     elif time_val.endswith('d'):
#         return timedelta(days=num)
#     elif time_val.endswith('M'):
#         return timedelta(days=(num*30))  # Yeah this is approximate
#     elif time_val.endswith('y'):
#         return timedelta(days=(num*365)) # Sorry, no leap year support
# 
# def none_fix(val):
#     """
#     If *val* is a string that utlimately means 'none', return None.  Otherwise
#     return *val* as-is.  Examples::
# 
#         >>> none_fix('none')
#         None
#         >>> none_fix('0')
#         None
#         >>> none_fix('whatever')
#         'whatever'
#     """
#     if isinstance(val, basestring) and val.lower() in ['none', '0', 'no']:
#         return None
#     else:
#         return val
# 
# def gen_self_signed_ssl(path=None):
#     """
#     Generates a self-signed SSL certificate using `pyOpenSSL` or the
#     `openssl <http://www.openssl.org/docs/apps/openssl.html>`_ command
#     depending on what's available,  The resulting key/certificate will use the
#     RSA algorithm at 4096 bits.
#     """
#     try:
#         import OpenSSL
#         # Direct OpenSSL library calls are better than executing commands...
#         gen_self_signed_func = gen_self_signed_pyopenssl
#     except ImportError:
#         gen_self_signed_func = gen_self_signed_openssl
#     try:
#         gen_self_signed_func(path=path)
#     except SSLGenerationError as e:
#         logging.error(_(
#             "Error generating self-signed SSL key/certificate: %s" % e))


# Path: applications/log.py
import os.path, sys, logging
import socket
    import simplejson as json
    import json
    import curses  # type: ignore
    import colorama
from applications.utils import mkdir_p
from applications.utils import getsettings,convert_to_timedelta,none_fix,gen_self_signed_ssl
from tornado import locale

    configure = False
    login_url ='/auth'
    static_url_prefix = '/static/'
    log_rotate_mode = 'size'
    logging = 'info'
    static_url = os.path.join(settings_base, 'static')
    session_logging = True
    log_file_num_backups = 10
    log_file_prefix = os.path.join(settings_base, 'log')
    if not os.path.exists(log_file_prefix):
        mkdir_p(log_file_prefix)
        os.chmod(log_file_prefix, 0o770)
    #if not check_write_permissions(uid, log_file_prefix):
        #recursive_chown(log_file_prefix, uid, gid)
    if not url_prefix.endswith('/'):
        url_prefix += '/' 
    global TIMEOUT
    TIMEOUT = convert_to_timedelta(session_timeout)
    api_timestamp_window = convert_to_timedelta(api_timestamp_window)
    auth = none_fix(auth)
    # Check to make sure we have a certificate and keyfile and generate fresh
    # ones if not.
    if not disable_ssl:
        if not os.path.exists(keyfile):
            ssl_base = os.path.dirname(keyfile)
            if not os.path.exists(ssl_base):
                mkdir_p(ssl_base)
            gen_self_signed_ssl(path=ssl_base)
        if not os.path.exists(certificate):
            ssl_base = os.path.dirname(certificate)

            gen_self_signed_ssl(path=ssl_base)   