#!/usr/bin/env python

import os
import sys
import pprint
import logging
import optparse

import aimes.bundle

DEFAULT_MONGODB_URL = 'mongodb://ec2-184-72-89-141.compute-1.amazonaws.com:27017/bundle_v0_1/'
DEFAULT_MONGODB_URL = 'mongodb://localhost:27017/bundle_v0_1/'
# TODO somehow setenv AIMES_BUNDLE_CONFIG
        
        
# ------------------------------------------------------------------------------
#
def parse_options():

    parser = optparse.OptionParser (add_help_option=False)

    parser.add_option ('-c', '--config-file', dest='config_file', default=None)
    parser.add_option ('-m', '--mode',        dest='mode',        default='once') 
    parser.add_option ('-u', '--url',         dest='url',         default=DEFAULT_MONGODB_URL) 
    parser.add_option ('-v', '--verbose',     dest='verbose',     action ='store_true') 
    parser.add_option ('-h', '--help',        dest='help',        action ='store_true') 

    return parser.parse_args()


# ------------------------------------------------------------------------------
#
def usage(msg=None):

    if msg:
        print "\n        ERROR  : %s" % msg

    print """
        usage  : %s -c <config> [-m <mode>] [-u url] [-v] [-h]
        example: %s -c bundle.cfg -m mongodb -u mongodb://localhost/

        options:
            -c --config-file
                location of the bundle configuration file (mandatory)
           
            -m --mode
                specify connectivity mode: once, mongodb or pyro4 (default: once)
           
            -u --url
                specify communication endpoint for mongodb 
                default: %s
           
            -v --verbose
                verbose operation (default: no)
           
            -h --help
                print help (default: no)


        modes:

            once   : the bundle manager will start agents according to the
                     config file, collect the information gathered by the
                     agents, and print them on stdout.
            mongodb: the bundle manager will start agents according to the
                     config file, collect the information gathered by the
                     agents, and store it in a mongodb for later query by
                     clients.
            pyro4  : the bundle manager will start agents according to the
                     config file, collect the information gathered by the
                     agents, and provide it as a pyro4 shared object structure.

            For both mongodb and pyro4 modes, the agent will got into background
            operation and will recollect live information from the agents every
            60 seconds, ie. it will become a dameon.


""" % (sys.argv[0], sys.argv[0], DEFAULT_MONGODB_URL)

    if msg :
        sys.exit (-1)

    else :
        sys.exit (0)
        

# ------------------------------------------------------------------------------
#
def main(argv=None):

    options, args = parse_options()

    help         = options.help
    config_file  = options.config_file
    mode         = options.mode
    url          = options.url
    verbose      = options.verbose

    if help :
        usage ()

    if args :
        usage ("cannot handle arguments %s" % str(args))

    if not config_file:
        usage("config file not specified")

    # we need to make path to bundle config absolute (for daemon)
    config_file = os.path.abspath (config_file) 

    if mode not in ['once', 'pyro4', 'mongodb'] :
        usage("mode '%s' not supported" % mode)

    if not os.path.isfile(config_file):
        usage("config file %s does not exist" % config_file)

    if verbose:
        logging.basicConfig(format='%(asctime)s %(levelname)s:%(name)s:%(filename)s:%(lineno)s:%(message)s',
            level=logging.DEBUG)
    else:
        logging.basicConfig(format='%(asctime)s %(levelname)s:%(name)s:%(filename)s:%(lineno)s:%(message)s',
            level=logging.ERROR)



    if mode == 'pyro4' :
        try:
            import Pyro4
        except ImportError:
            logging.critical("Bundle Manager depends on Pyro4 package installation")
            sys.exit(1)
        bm = aimes.bundle.impl.BundleManager()
        bm.load_cluster_credentials(config_file)
        Pyro4.Daemon.serveSimple({bm:"BundleManager"}, ns = True)

    elif mode == 'mongodb' :

        bm = aimes.bundle.impl.BundleManager()
        bm.start_daemon (config_file, url)


    elif mode == 'once' :

        # Note that this mode does not use the bundle api, but the
        # implementation level API -- it mostly exists for debuggin purposes!
        bm = aimes.bundle.impl.BundleManager()
        bm.load_cluster_credentials(config_file)
        ret = bm.get_data ()

        for cluster in ret['cluster_list'] :
            print "===> %s" % cluster
            print
            print "--   config"
            pprint.pprint (ret['cluster_config'][cluster])
            print
            print "--   workload"
            pprint.pprint (ret['cluster_workload'][cluster])
            print
            print "--   bandwidth"
            pprint.pprint (ret['cluster_bandwidth'][cluster])
            print
            print

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


# ------------------------------------------------------------------------------

