#!/usr/bin/env python
# Copyright (c) 2009, Michael Gorven
# Released under terms of the MIT/X/Expat Licence. See COPYING for details.

from sys import path
from optparse import OptionParser

from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util

path.insert(0, '.')

from ibid.compat import json

parser = OptionParser(usage='%prog [options] message <message> | plugin <feature> <method> <parameters>')
parser.add_option('-s', '--server', help='Hostname of Ibid instance')
parser.add_option('-p', '--port', help='Port number of Ibid instance')

parser.set_defaults(server='localhost', port=8789)
options, args = parser.parse_args()
command = args[0].lower()

factory = pb.PBClientFactory()
reactor.connectTCP(options.server, options.port, factory)
d = factory.getRootObject()

if command == 'message':
    if len(args) < 2:
        parser.error(u'Please specify a message to send.')
    d.addCallback(lambda object: object.callRemote('message', ' '.join(args[1:])))

elif command == 'plugin':
    if len(args) < 3:
        parser.error(u'Not enough arguments.')
    d.addCallback(lambda root: root.callRemote('get_plugin', args[1]))
    pargs = []
    kwargs = {}
    for arg in args[3:]:
        key = None
        if arg.find('=') != -1:
            key, value = arg.split('=', 1)
        else:
            value = arg

        try:
            value = json.loads(value)
        except ValueError, e:
            pass

        if key:
            kwargs[key] = value
        else:
            pargs.append(value)

    d.addCallback(lambda plugin: plugin.callRemote(args[2], *pargs, **kwargs))

d.addCallback(lambda response: json.dumps(response))
d.addErrback(lambda reason: 'Error: %s' % str(reason.value))
d.addCallback(util.println)
d.addCallback(lambda _: reactor.stop())
reactor.run()

# vi: set et sta sw=4 ts=4:
