# Path: amivapi/bootstrap.py
# def create_app(config_file=None, **kwargs):
#     """
#     Create a new eve app object and initialize everything.
# 
#     User configuration can be loaded in the following order:
# 
#     1. Use the `config_file` arg to specify a file
#     2. If `config_file` is `None`, you set the environment variable
#        `AMIVAPI_CONFIG` to the path of your config file
#     3. If no environment variable is set either, `config.py` in the current
#        working directory is used
# 
#     Args:
#         config (path): Specify config file to use.
#         kwargs: All other key-value arguments will be used to update the config
#     Returns:
#         (Eve): The Eve application
#     """
#     # Load config
#     config = Config(getcwd())
#     config.from_object("amivapi.settings")
# 
#     # Specified path > environment var > default path; abspath for better log
#     user_config = abspath(config_file or getenv('AMIVAPI_CONFIG', 'config.py'))
#     try:
#         config.from_pyfile(user_config)
#         config_status = "Config loaded: %s" % user_config
#     except IOError:
#         config_status = "No config found."
# 
#     config.update(kwargs)
# 
#     # Initialize empty domain to create Eve object, register resources later
#     config['DOMAIN'] = {}
# 
#     app = Eve("amivapi",  # Flask needs this name to find the static folder
#               settings=config,
#               validator=ValidatorAMIV)
#     app.logger.info(config_status)
# 
#     # Set up error logging with sentry
#     init_sentry(app)
# 
#     # Create LDAP connector
#     ldap.init_app(app)
# 
#     # Initialize modules to register resources, validation, hooks, auth, etc.
#     users.init_app(app)
#     auth.init_app(app)
#     events.init_app(app)
#     groups.init_app(app)
#     blacklist.init_app(app)
#     joboffers.init_app(app)
#     studydocs.init_app(app)
#     cascade.init_app(app)
#     cron.init_app(app)
#     documentation.init_app(app)
# 
#     # Fix that eve doesn't run hooks on embedded documents
#     app.on_fetched_item += utils.run_embedded_hooks_fetched_item
#     app.on_fetched_resource += utils.run_embedded_hooks_fetched_resource
# 
#     return app
# 
# Path: amivapi/cron.py
# def run_scheduled_tasks():
#     """ Check for scheduled task, which have passed the deadline and run them.
#     This needs an app context.
#     """
#     while True:
#         task = (current_app.data.driver.db['scheduled_tasks']
#                 .find_one_and_delete(
#                     {'time': {'$lte': datetime.utcnow()}}))
# 
#         if task is None:
#             return
# 
#         args = pickle.loads(task['args'])
#         func = schedulable_functions[task['function']]
#         func(*args)
# 
# Path: amivapi/ldap.py
# def init_app(app):
# def authenticate_user(cn, password):
# def sync_one(cn):
# def sync_all():
# def _search(query):
# def _escape(query):
# def _process_data(data):
# def _create_or_update_user(ldap_data):
# 
# Path: amivapi/groups/mailing_lists.py
# def updated_group(updates, original):
#     """Update group mailing lists if any address changes."""
#     # Remove no longer needed forwards
#     if 'receive_from' in updates:
#         original_addresses = original.get('receive_from') or []
#         remove_files(address for address in original_addresses
#                      if address not in updates['receive_from'])
#     # Update remaining forwards
#     if ('receive_from' in updates) or ('forward_to' in updates):
#         make_files(original['_id'])


from os import listdir, remove
from os.path import join, isdir
from datetime import datetime as dt
from time import sleep
from click import argument, echo, group, option, Path, Choice, ClickException
from amivapi.bootstrap import create_app
from amivapi.cron import run_scheduled_tasks
from amivapi import ldap
from amivapi.groups.mailing_lists import updated_group
    import bjoern
                echo("Synchronized %i users." % len(res))
            else:
                for user in nethz:
                    if ldap.sync_one(user) is not None:
                        echo("Successfully synchronized '%s'." % user)
                    else:
                        echo("Could not synchronize '%s'." % user)


@cli.command()
@config_option
@argument('mode', type=Choice(['prod', 'dev']))
def run(config, mode):
    """Run production/development server.

    Two modes of operation are available:

    - dev: Run a development server

    - prod: Run a production server (requires the `bjoern` module)
    """
    if mode == 'dev':
        app = create_app(config_file=config,
                         ENV='development',
                         DEBUG=True,
                         TESTING=True)
        app.run(threaded=True, host='0.0.0.0', port=5000)
    elif mode == 'prod':
        if bjoern:
            echo('Starting bjoern on port 8080...')

# Path: amivapi/bootstrap.py
# def create_app(config_file=None, **kwargs):
#     """
#     Create a new eve app object and initialize everything.
# 
#     User configuration can be loaded in the following order:
# 
#     1. Use the `config_file` arg to specify a file
#     2. If `config_file` is `None`, you set the environment variable
#        `AMIVAPI_CONFIG` to the path of your config file
#     3. If no environment variable is set either, `config.py` in the current
#        working directory is used
# 
#     Args:
#         config (path): Specify config file to use.
#         kwargs: All other key-value arguments will be used to update the config
#     Returns:
#         (Eve): The Eve application
#     """
#     # Load config
#     config = Config(getcwd())
#     config.from_object("amivapi.settings")
# 
#     # Specified path > environment var > default path; abspath for better log
#     user_config = abspath(config_file or getenv('AMIVAPI_CONFIG', 'config.py'))
#     try:
#         config.from_pyfile(user_config)
#         config_status = "Config loaded: %s" % user_config
#     except IOError:
#         config_status = "No config found."
# 
#     config.update(kwargs)
# 
#     # Initialize empty domain to create Eve object, register resources later
#     config['DOMAIN'] = {}
# 
#     app = Eve("amivapi",  # Flask needs this name to find the static folder
#               settings=config,
#               validator=ValidatorAMIV)
#     app.logger.info(config_status)
# 
#     # Set up error logging with sentry
#     init_sentry(app)
# 
#     # Create LDAP connector
#     ldap.init_app(app)
# 
#     # Initialize modules to register resources, validation, hooks, auth, etc.
#     users.init_app(app)
#     auth.init_app(app)
#     events.init_app(app)
#     groups.init_app(app)
#     blacklist.init_app(app)
#     joboffers.init_app(app)
#     studydocs.init_app(app)
#     cascade.init_app(app)
#     cron.init_app(app)
#     documentation.init_app(app)
# 
#     # Fix that eve doesn't run hooks on embedded documents
#     app.on_fetched_item += utils.run_embedded_hooks_fetched_item
#     app.on_fetched_resource += utils.run_embedded_hooks_fetched_resource
# 
#     return app
# 
# Path: amivapi/cron.py
# def run_scheduled_tasks():
#     """ Check for scheduled task, which have passed the deadline and run them.
#     This needs an app context.
#     """
#     while True:
#         task = (current_app.data.driver.db['scheduled_tasks']
#                 .find_one_and_delete(
#                     {'time': {'$lte': datetime.utcnow()}}))
# 
#         if task is None:
#             return
# 
#         args = pickle.loads(task['args'])
#         func = schedulable_functions[task['function']]
#         func(*args)
# 
# Path: amivapi/ldap.py
# def init_app(app):
# def authenticate_user(cn, password):
# def sync_one(cn):
# def sync_all():
# def _search(query):
# def _escape(query):
# def _process_data(data):
# def _create_or_update_user(ldap_data):
# 
# Path: amivapi/groups/mailing_lists.py
# def updated_group(updates, original):
#     """Update group mailing lists if any address changes."""
#     # Remove no longer needed forwards
#     if 'receive_from' in updates:
#         original_addresses = original.get('receive_from') or []
#         remove_files(address for address in original_addresses
#                      if address not in updates['receive_from'])
#     # Update remaining forwards
#     if ('receive_from' in updates) or ('forward_to' in updates):
#         make_files(original['_id'])


# Path: amivapi/cli.py
from os import listdir, remove
from os.path import join, isdir
from datetime import datetime as dt
from time import sleep
from click import argument, echo, group, option, Path, Choice, ClickException
from amivapi.bootstrap import create_app
from amivapi.cron import run_scheduled_tasks
from amivapi import ldap
from amivapi.groups.mailing_lists import updated_group
    import bjoern

                echo("Synchronized %i users." % len(res))
            else:
                for user in nethz:
                    if ldap.sync_one(user) is not None:
                        echo("Successfully synchronized '%s'." % user)
                    else:
                        echo("Could not synchronize '%s'." % user)


@cli.command()
@config_option
@argument('mode', type=Choice(['prod', 'dev']))
def run(config, mode):
    """Run production/development server.

    Two modes of operation are available:

    - dev: Run a development server

    - prod: Run a production server (requires the `bjoern` module)
    """
    if mode == 'dev':
        app = create_app(config_file=config,
                         ENV='development',
                         DEBUG=True,
                         TESTING=True)
        app.run(threaded=True, host='0.0.0.0', port=5000)
    elif mode == 'prod':
        if bjoern:
            echo('Starting bjoern on port 8080...')

            bjoern.run(create_app(config_file=config), '0.0.0.0', 8080)