#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

import optparse
from qpid.messaging import *
from qpid.util import URL
from qpid.log import enable, DEBUG, WARN

def nameval(st):
  idx = st.find("=")
  if idx >= 0:
    name = st[0:idx]
    value = st[idx+1:]
  else:
    name = st
    value = None
  return name, value

def list_map_entries(m):
  r = ""
  for t in m:
    r += "%s=%s " % (t, m[t]) 
  return r

def get_qmfv2_result(m):
  if m.properties['x-amqp-0-10.app-id'] == 'qmf2':
    if m.properties['qmf.opcode'] == '_method_response':
      return m.content['_arguments']
    elif m.properties['qmf.opcode'] == '_exception':
      raise Exception("Error: %s" % list_map_entries(m.content['_values']))
    else: raise Exception("Invalid response received, unexpected opcode: %s" % m)
  else: raise Exception("Invalid response received, not a qmfv2 method: %s" % m)


parser = optparse.OptionParser(usage="usage: %prog [options] COMMAND ...",
                               description="Invoke the specified command.")
parser.add_option("-b", "--broker", default="localhost",
                  help="connect to specified BROKER (default %default)")
parser.add_option("-c", "--class", dest="qmfclass", default="broker", 
                  help="class of object on which command is being invoked (default %default)")
parser.add_option("-p", "--package", default="org.apache.qpid.broker",
                  help="package of object on which command is being invoked (default %default)")
parser.add_option("-i", "--id", default="amqp-broker",
                  help="identifier of object on which command is being invoked (default %default)")
parser.add_option("-a", "--address", default="qmf.default.direct/broker",
                  help="address to send commands to (default %default)")
parser.add_option("-t", "--timeout", type="float", default=5,
                  help="timeout in seconds to wait for response before exiting (default %default)")
parser.add_option("-v", dest="verbose", action="store_true",
                  help="enable logging")

opts, args = parser.parse_args()

if opts.verbose:
  enable("qpid", DEBUG)
else:
  enable("qpid", WARN)

if args:
  command = args.pop(0)
else:
  parser.error("command is required")


conn = Connection(opts.broker)
try:
  conn.open()
  ssn = conn.session()
  snd = ssn.sender(opts.address)
  reply_to = "qmf.default.direct/%s; {node: {type: topic}}" % str(uuid4())
  rcv = ssn.receiver(reply_to)

  object_name = "%s:%s:%s" % (opts.package, opts.qmfclass, opts.id)
  method_name = command
  arguments = {}
  for a in args:
    name, val = nameval(a)
    if val[0] == '{' or val[0] == '[':
      arguments[name] = eval(val)
    else:
      arguments[name] = val
  content = {
             "_object_id": {"_object_name": object_name},
             "_method_name": method_name,
             "_arguments": arguments
            } 
  msg = Message(reply_to=reply_to, content=content)
  msg.properties["x-amqp-0-10.app-id"] = "qmf2"
  msg.properties["qmf.opcode"] = "_method_request"
  snd.send(msg)

  try:
    print list_map_entries(get_qmfv2_result(rcv.fetch(timeout=opts.timeout)))
  except Empty:
    print "No response received!"
  except Exception, e:
    print e
except ReceiverError, e:
  print e
except KeyboardInterrupt:
  pass

conn.close()
