#!/usr/bin/python -tt

# Twisted hosts our RESTful APIs and help with 0MQ events.
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource

# 0MQ takes care of all messaging.
from ponycloud.common.tzmq import Router

# Command line arguments follow the GNU conventions.
from getopt import gnu_getopt
from sys import argv

# Configuration is stored in a boring ini file.
from ConfigParser import ConfigParser

# The application itself also comes in handy... ;-)
from ponycloud.luna import *


if __name__ == '__main__':
    def do_start(config):
        # 0MQ router to connect to Sparkle.
        router = Router(default_recipient='sparkle')\
                    .connect(config.get('zmq', 'endpoint'))

        # Prepare the manager that takes care of business logic.
        manager = Manager(router)

        # Dispatch events to manager.
        router.on_message = make_event_handler(manager)

        # Schedule call to the manager.
        reactor.callLater(0, manager.start)

        # Run twisted.
        reactor.run()


    def do_help(*args, **kwargs):
        print 'Usage: luna [--config=/etc/cloud/luna.ini]'
        print 'Runs luna daemon with given configuration.'
        print ''
        print 'OPTIONS:'
        print '  --help, -h          Display this help.'
        print '  --version, -V       Display version info.'
        print ''
        print '  --config, -c file   Load alternative configuration file.'
        print '                      Defaults to /etc/cloud/luna.ini.'
        print ''
        print 'Report bugs at <http://github.com/ponycloud/>.'

    def do_version(*args, **kwargs):
        print 'luna (PonyCloud) 1'

    # Parse command line arguments.
    opts, args = gnu_getopt(argv, 'hVc:', ['help', 'version', 'config='])

    action = do_start
    config_path = '/etc/cloud/luna.ini'

    for k, v in opts:
        if k in ('--help', '-h'):
            action = do_help
        elif k in ('--version', '-V'):
            action = do_version
        elif k in ('--config', '-c'):
            config_path = v

    # Load the configuration from file.
    config = ConfigParser()
    config.read(config_path)

    # Perform the selected action.
    action(config=config)

# vim:set sw=4 ts=4 et:
# -*- coding: utf-8 -*-
