#!/usr/bin/env python
"""
    Author: John E. Vincent
	Email:	lusis.org+github.com@gmail.com
"""

import argparse
import subprocess, shlex
import pprint
from vogeler.vogeler import VogelerClient, VogelerPlugin, VogelerException
from platform import node

pp = pprint.PrettyPrinter(indent=4)

def process_request(request):

    try:
        results = plugins.execute_plugin(request)
        c.message(results)
        if args.oneshot == True:
            print "Oneshot requested. Running command %s and exiting" % request
            shutdown()
    except VogelerException:
        print "VogelerException raised"

def startup():
    c.monitor()

def shutdown():
    print "Shutting down"
    c.close()
    return 0
    exit

def execute_run(pargs):
    global plugins, c
    try:
        if pargs.plugindir:
            plugins = VogelerPlugin(plugin_dir=pargs.plugindir)
        else:
            plugins = VogelerPlugin()
        c = VogelerClient(callback_function=process_request)
        startup()
    except KeyboardInterrupt:
        shutdown()

def list_plugins(pargs):
    global plugins
    try:
        if pargs.plugindir == '':
            plugins = VogelerPlugin()
            if len(plugins.authorized_plugins) == 0:
                print "No plugins are registered with the system"
            else:
                print plugins.plugin_registry
        else:
            plugins = VogelerPlugin(plugin_dir=pargs.plugindir)
            pp.pprint(plugins.plugin_registry)
    except:
        raise

if __name__ == "__main__":
    appdesc = 'Vogeler client daemon'
    parser = argparse.ArgumentParser(description=appdesc)
    subparsers = parser.add_subparsers(help='commands')
    parser.add_argument('--plugindir', '-p', help='Specifiy location of trusted plugins', required=False)
    
    # runtime options
    runtime_parser = subparsers.add_parser('run', help='Runtime commands')
    runtime_parser.add_argument('--oneshot', '-o', action="store_true", default=False, help='Exit after first command')
    runtime_parser.add_argument('--allow-unsafe', '-u', action="store_true", default=False, help='WARNING: This options accepts any command that the client recieves. Use with caution!')
    runtime_parser.set_defaults(func=execute_run)

    # Noop options
    list_parser = subparsers.add_parser('list', help='List plugins')
    list_parser.add_argument('--system', '-s', action="store_true", default=False, help='Show system-wide plugins', required=False)
    list_parser.set_defaults(func=list_plugins)

    args = parser.parse_args()
    args.func(args)

# vim: set ts=4 et sw=4 sts=4 sta filetype=python :
