#!/usr/bin/python

import nilmdb.server
import argparse
import os
import socket

def main():
    """Main entry point for the 'nilmdb-server' command line script"""

    parser = argparse.ArgumentParser(
        description = 'Run the NilmDB server',
        formatter_class = argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("-V", "--version", action="version",
                        version = nilmdb.__version__)

    group = parser.add_argument_group("Standard options")
    group.add_argument('-a', '--address',
                       help = 'Only listen on the given address',
                       default = '0.0.0.0')
    group.add_argument('-p', '--port', help = 'Listen on the given port',
                       type = int, default = 12380)
    group.add_argument('-d', '--database', help = 'Database directory',
                       default = "./db")
    group.add_argument('-q', '--quiet', help = 'Silence output',
                       action = 'store_true')
    group.add_argument('-t', '--traceback',
                       help = 'Provide tracebacks in client errors',
                       action = 'store_true', default = False)

    group = parser.add_argument_group("Debug options")
    group.add_argument('-y', '--yappi', help = 'Run under yappi profiler and '
                       'invoke interactive shell afterwards',
                       action = 'store_true')

    args = parser.parse_args()

    # Create database object.  Needs to be serialized before passing
    # to the Server.
    db = nilmdb.utils.serializer_proxy(nilmdb.server.NilmDB)(args.database)

    # Configure the server
    if args.quiet:
        embedded = True
    else:
        embedded = False
    server = nilmdb.server.Server(db,
                                  host = args.address,
                                  port = args.port,
                                  embedded = embedded,
                                  force_traceback = args.traceback)

    # Print info
    if not args.quiet:
        print "Version: %s" % nilmdb.__version__
        print "Database: %s" % (os.path.realpath(args.database))
        if args.address == '0.0.0.0' or args.address == '::':
            host = socket.getfqdn()
        else:
            host = args.address
        print "Server URL: http://%s:%d/" % ( host, args.port)
        print "----"

    # Run it
    if args.yappi:
        print "Running in yappi"
        try:
            import yappi
            yappi.start()
            server.start(blocking = True)
        finally:
            yappi.stop()
            yappi.print_stats(sort_type = yappi.SORTTYPE_TTOT, limit = 50)
            from IPython import embed
            embed(header = "Use the yappi object to explore further, "
                  "quit to exit")
    else:
        server.start(blocking = True)

    # Clean up
    if not args.quiet:
        print "Closing database"
        db.close()

if __name__ == "__main__":
    main()
