#!/usr/bin/python
#
# Copyright (c) 2009, 2010, 2012, 2013
#  Adam Tauno Williams <awilliam@whitemice.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import getopt
import sys
import os
from coils.core import initialize_COILS, BundleManager
from coils.core import change_to_backend_usergroup
from coils.net import HTTPService, SMTPService


def usage():
    print """
        Run an OpenGroupware COILS Logic command with specified parameters.
        --help          Display this message.
        --service=      The service to run.
        --silent        Close standard-in/standard-out
        --store=        Set the BLOB store root.
           defaults to "/var/lib/opengroupware.org"
        --group=        Set the group to run services as; defaults to "skyrix"
        --user=         Set the user to run services as; defaults to "ogo".
        --asuser        Do not change user/group; run as the current user.

        Operation is also controlled by the following environment variables:

          COILS_EXTRA_MODULES : Specify a CSSS list of additional, possibly
            custom, modules to load and inspect for commands and protocolsl.
          COILS_BANNED_MODULES : Specify a CSV list of modules that should not
            be loaded even if or specified in the server's configuration.
          COILS_BANNED_SERVICES : A CSV list of services that even if d
            discovered or specified in the server's configuraiton should not
            be started.

    """
    return


def main(argv):
    # Process command line arguements
    if (len(argv) == 0):
        usage()
        sys.exit(2)

    silent = False
    component = None
    username = 'ogo'
    groupname = 'skyrix'
    storeroot = None
    changeuser = True
    add_modules = []
    ban_modules = []

    try:
        opts, args = getopt.getopt(
            argv,
            'hctaugsx',
            ['help', 'service=', 'user',
             'asuser', 'group', 'add-bundle=',
             'ban-bundle=', 'silent', ]
        )
    except getopt.GetoptError, e:
        print e
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-c", "--silent"):
            silent = True
        elif opt in ("-t", "--service"):
            component = arg
        elif opt in ("-a", "--asuser"):
            changeuser = False
        elif opt in ("-u", "--user"):
            username = arg
        elif opt in ("-g", "--group"):
            groupname = arg
        elif opt in ("-s", "--store"):
            storeroot = arg
        elif opt in ("-i", "--add-bundle"):
            add_modules.append(arg)
        elif opt in ("-x", "--ban-bundle"):
            ban_modules.append(arg)

    if (changeuser):
        change_to_backend_usergroup(username, groupname)

    # Extra modules to add can also be specified in the environment
    env_add_modules = os.getenv('COILS_EXTRA_MODULES')
    if env_add_modules:
        for module_name in env_add_modules.split(','):
            add_modules.append(module_name.strip())

    # Modules to ban can also be specified in the environment
    env_ban_modules = os.getenv('COILS_BANNED_MODULES')
    if env_ban_modules:
        for module_name in env_ban_modules.split(','):
            ban_modules.append(module_name.strip())

    initialize_COILS({'store_root': storeroot,
                      'extra_modules': add_modules,
                      'banned_modules': ban_modules, })

    service = BundleManager.get_service(component)
    if not service:
        if component == 'coils.http':
            service = HTTPService
        elif component == 'coils.smtpd':
            service = SMTPService
    if service:
        instance = service()
        instance.run(silent=silent)
    else:
        print('Discovered no such service as "{0}"'.format(component, ))

if __name__ == "__main__":
    main(sys.argv[1:])
