#!/usr/bin/env python

#   The contents of this file are subject to the Mozilla Public License
#   Version 1.1 (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.mozilla.org/MPL/
#
#   Software distributed under the License is distributed on an "AS IS"
#   basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
#   License for the specific language governing rights and limitations
#   under the License.
#
#   The Original Code is RabbitMQ Management Plugin.
#
#   The Initial Developer of the Original Code is GoPivotal, Inc.
#   Copyright (c) 2010-2014 GoPivotal, Inc.  All rights reserved.

import sys
if sys.version_info[0] < 2 or sys.version_info[1] < 6:
    print "Sorry, rabbitmqadmin requires at least Python 2.6."
    sys.exit(1)

from ConfigParser import ConfigParser, NoSectionError
from optparse import OptionParser, TitledHelpFormatter
import httplib
import urllib
import urlparse
import base64
import json
import os
import socket

VERSION = '3.4.3'

LISTABLE = {'connections': {'vhost': False, 'cols': ['name','user','channels']},
            'channels':    {'vhost': False, 'cols': ['name', 'user']},
            'consumers':   {'vhost': True},
            'exchanges':   {'vhost': True,  'cols': ['name', 'type']},
            'queues':      {'vhost': True,  'cols': ['name', 'messages']},
            'bindings':    {'vhost': True,  'cols': ['source', 'destination',
                                                     'routing_key']},
            'users':       {'vhost': False},
            'vhosts':      {'vhost': False, 'cols': ['name', 'messages']},
            'permissions': {'vhost': False},
            'nodes':       {'vhost': False, 'cols': ['name','type','mem_used']},
            'parameters':  {'vhost': False, 'json': ['value']},
            'policies':    {'vhost': False, 'json': ['definition']}}

SHOWABLE = {'overview': {'vhost': False, 'cols': ['rabbitmq_version',
                                                  'cluster_name',
                                                  'queue_totals.messages',
                                                  'object_totals.queues']}}

PROMOTE_COLUMNS = ['vhost', 'name', 'type',
                   'source', 'destination', 'destination_type', 'routing_key']

URIS = {
    'exchange':   '/exchanges/{vhost}/{name}',
    'queue':      '/queues/{vhost}/{name}',
    'binding':    '/bindings/{vhost}/e/{source}/{destination_char}/{destination}',
    'binding_del':'/bindings/{vhost}/e/{source}/{destination_char}/{destination}/{properties_key}',
    'vhost':      '/vhosts/{name}',
    'user':       '/users/{name}',
    'permission': '/permissions/{vhost}/{user}',
    'parameter':  '/parameters/{component}/{vhost}/{name}',
    'policy':     '/policies/{vhost}/{name}'
    }

DECLARABLE = {
    'exchange':   {'mandatory': ['name', 'type'],
                   'json':      ['arguments'],
                   'optional':  {'auto_delete': 'false', 'durable': 'true',
                                 'internal': 'false', 'arguments': {}}},
    'queue':      {'mandatory': ['name'],
                   'json':      ['arguments'],
                   'optional':  {'auto_delete': 'false', 'durable': 'true',
                                 'arguments': {}, 'node': None}},
    'binding':    {'mandatory': ['source', 'destination'],
                   'json':      ['arguments'],
                   'optional':  {'destination_type': 'queue',
                                 'routing_key': '', 'arguments': {}}},
    'vhost':      {'mandatory': ['name'],
                   'optional':  {'tracing': None}},
    'user':       {'mandatory': ['name', 'password', 'tags'],
                   'optional':  {}},
    'permission': {'mandatory': ['vhost', 'user', 'configure', 'write', 'read'],
                   'optional':  {}},
    'parameter':  {'mandatory': ['component', 'name', 'value'],
                   'json':      ['value'],
                   'optional':  {}},
    # Priority is 'json' to convert to int
    'policy':     {'mandatory': ['name', 'pattern', 'definition'],
                   'json':      ['definition', 'priority'],
                   'optional':  {'priority' : 0, 'apply-to': None}}
    }

DELETABLE = {
    'exchange':   {'mandatory': ['name']},
    'queue':      {'mandatory': ['name']},
    'binding':    {'mandatory': ['source', 'destination_type', 'destination',
                                 'properties_key']},
    'vhost':      {'mandatory': ['name']},
    'user':       {'mandatory': ['name']},
    'permission': {'mandatory': ['vhost', 'user']},
    'parameter':  {'mandatory': ['component', 'name']},
    'policy':     {'mandatory': ['name']}
    }

CLOSABLE = {
    'connection': {'mandatory': ['name'],
                   'optional':  {},
                   'uri':       '/connections/{name}'}
    }

PURGABLE = {
    'queue': {'mandatory': ['name'],
              'optional':  {},
              'uri':       '/queues/{vhost}/{name}/contents'}
    }

EXTRA_VERBS = {
    'publish': {'mandatory': ['routing_key'],
                'optional':  {'payload': None,
                              'properties': {},
                              'exchange': 'amq.default',
                              'payload_encoding': 'string'},
                'json':      ['properties'],
                'uri':       '/exchanges/{vhost}/{exchange}/publish'},
    'get':     {'mandatory': ['queue'],
                'optional':  {'count': '1', 'requeue': 'true',
                              'payload_file': None, 'encoding': 'auto'},
                'uri':       '/queues/{vhost}/{queue}/get'}
}

for k in DECLARABLE:
    DECLARABLE[k]['uri'] = URIS[k]

for k in DELETABLE:
    DELETABLE[k]['uri'] = URIS[k]
    DELETABLE[k]['optional'] = {}
DELETABLE['binding']['uri'] = URIS['binding_del']

def short_usage():
    return "rabbitmqadmin [options] subcommand"

def title(name):
    return "\n%s\n%s\n\n" % (name, '=' * len(name))

def subcommands_usage():
    usage = """Usage
=====
  """ + short_usage() + """

  where subcommand is one of:
""" + title("Display")

    for l in LISTABLE:
        usage += "  list {0} [<column>...]\n".format(l)
    for s in SHOWABLE:
        usage += "  show {0} [<column>...]\n".format(s)
    usage += title("Object Manipulation")
    usage += fmt_usage_stanza(DECLARABLE,  'declare')
    usage += fmt_usage_stanza(DELETABLE,   'delete')
    usage += fmt_usage_stanza(CLOSABLE,    'close')
    usage += fmt_usage_stanza(PURGABLE,    'purge')
    usage += title("Broker Definitions")
    usage += """  export <file>
  import <file>
"""
    usage += title("Publishing and Consuming")
    usage += fmt_usage_stanza(EXTRA_VERBS, '')
    usage += """
  * If payload is not specified on publish, standard input is used

  * If payload_file is not specified on get, the payload will be shown on
    standard output along with the message metadata

  * If payload_file is specified on get, count must not be set
"""
    return usage

def config_usage():
    usage = "Usage\n=====\n" + short_usage()
    usage += "\n" + title("Configuration File")
    usage += """  It is possible to specify a configuration file from the command line.
  Hosts can be configured easily in a configuration file and called
  from the command line.
"""
    usage += title("Example")
    usage += """  # rabbitmqadmin.conf.example START

  [host_normal]
  hostname = localhost
  port = 15672
  username = guest
  password = guest
  declare_vhost = / # Used as default for declare / delete only
  vhost = /         # Used as default for declare / delete / list

  [host_ssl]
  hostname = otherhost
  port = 15672
  username = guest
  password = guest
  ssl = True
  ssl_key_file = /path/to/key.pem
  ssl_cert_file = /path/to/cert.pem

  # rabbitmqadmin.conf.example END
"""
    usage += title("Use")
    usage += """  rabbitmqadmin -c rabbitmqadmin.conf.example -N host_normal ..."""
    return usage

def more_help():
    return """
More Help
=========

For more help use the help subcommand:

  rabbitmqadmin help subcommands  # For a list of available subcommands
  rabbitmqadmin help config       # For help with the configuration file
"""

def fmt_usage_stanza(root, verb):
    def fmt_args(args):
        res = " ".join(["{0}=...".format(a) for a in args['mandatory']])
        opts = " ".join("{0}=...".format(o) for o in args['optional'].keys())
        if opts != "":
            res += " [{0}]".format(opts)
        return res

    text = ""
    if verb != "":
        verb = " " + verb
    for k in root.keys():
        text += " {0} {1} {2}\n".format(verb, k, fmt_args(root[k]))
    return text

default_options = { "hostname"        : "localhost",
                    "port"            : "15672",
                    "declare_vhost"   : "/",
                    "username"        : "guest",
                    "password"        : "guest",
                    "ssl"             : False,
                    "verbose"         : True,
                    "format"          : "table",
                    "depth"           : 1,
                    "bash_completion" : False }


class MyFormatter(TitledHelpFormatter):
    def format_epilog(self, epilog):
        return epilog

parser = OptionParser(usage=short_usage(),
                      formatter=MyFormatter(),
                      epilog=more_help())

def make_parser():
    def add(*args, **kwargs):
        key = kwargs['dest']
        if key in default_options:
            default = " [default: %s]" % default_options[key]
            kwargs['help'] = kwargs['help'] + default
        parser.add_option(*args, **kwargs)

    add("-c", "--config", dest="config",
        help="configuration file [default: ~/.rabbitmqadmin.conf]",
        metavar="CONFIG")
    add("-N", "--node", dest="node",
        help="node described in the configuration file [default: 'default'" + \
             " only if configuration file is specified]",
        metavar="NODE")
    add("-H", "--host", dest="hostname",
        help="connect to host HOST" ,
        metavar="HOST")
    add("-P", "--port", dest="port",
        help="connect to port PORT",
        metavar="PORT")
    add("-V", "--vhost", dest="vhost",
        help="connect to vhost VHOST [default: all vhosts for list, '/' for declare]",
        metavar="VHOST")
    add("-u", "--username", dest="username",
        help="connect using username USERNAME",
        metavar="USERNAME")
    add("-p", "--password", dest="password",
        help="connect using password PASSWORD",
        metavar="PASSWORD")
    add("-q", "--quiet", action="store_false", dest="verbose",
        help="suppress status messages")
    add("-s", "--ssl", action="store_true", dest="ssl",
        help="connect with ssl")
    add("--ssl-key-file", dest="ssl_key_file",
        help="PEM format key file for SSL")
    add("--ssl-cert-file", dest="ssl_cert_file",
        help="PEM format certificate file for SSL")
    add("-f", "--format", dest="format",
        help="format for listing commands - one of [" + ", ".join(FORMATS.keys())  + "]")
    add("-S", "--sort", dest="sort", help="sort key for listing queries")
    add("-R", "--sort-reverse", action="store_true", dest="sort_reverse",
        help="reverse the sort order")
    add("-d", "--depth", dest="depth",
        help="maximum depth to recurse for listing tables")
    add("--bash-completion", action="store_true",
        dest="bash_completion",
        help="Print bash completion script")
    add("--version", action="store_true",
        dest="version",
        help="Display version and exit")

def default_config():
    home = os.getenv('USERPROFILE') or os.getenv('HOME')
    if home is not None:
        config_file = home + os.sep + ".rabbitmqadmin.conf"
        if os.path.isfile(config_file):
            return config_file
    return None

def make_configuration():
    make_parser()
    (options, args) = parser.parse_args()
    setattr(options, "declare_vhost", None)
    if options.version:
        print_version()
    if options.config is None:
        config_file = default_config()
        if config_file is not None:
            setattr(options, "config", config_file)
    else:
        if not os.path.isfile(options.config):
            assert_usage(False,
                "Could not read config file '%s'" % options.config)

    if options.node is None and options.config:
        options.node = "default"
    else:
        options.node = options.node
    for (key, val) in default_options.items():
        if getattr(options, key) is None:
            setattr(options, key, val)

    if options.config is not None:
        config = ConfigParser()
        try:
            config.read(options.config)
            new_conf = dict(config.items(options.node))
        except NoSectionError, error:
            if options.node == "default":
                pass
            else:
                assert_usage(False, ("Could not read section '%s' in config file"  +
                             " '%s':\n   %s") %
                             (options.node, options.config, error))
        else:
            for key, val in new_conf.items():
                setattr(options, key, val)

    return (options, args)

def assert_usage(expr, error):
    if not expr:
        output("\nERROR: {0}\n".format(error))
        output("{0} --help for help\n".format(os.path.basename(sys.argv[0])))
        sys.exit(1)

def print_version():
    output("rabbitmqadmin {0}".format(VERSION))
    sys.exit(0)

def column_sort_key(col):
    if col in PROMOTE_COLUMNS:
        return (1, PROMOTE_COLUMNS.index(col))
    else:
        return (2, col)

def main():
    (options, args) = make_configuration()
    if options.bash_completion:
        print_bash_completion()
        exit(0)
    assert_usage(len(args) > 0, 'Action not specified')
    mgmt = Management(options, args[1:])
    mode = "invoke_" + args[0]
    assert_usage(hasattr(mgmt, mode),
                 'Action {0} not understood'.format(args[0]))
    method = getattr(mgmt, "invoke_%s" % args[0])
    method()

def output(s):
    print maybe_utf8(s, sys.stdout)

def die(s):
    sys.stderr.write(maybe_utf8("*** {0}\n".format(s), sys.stderr))
    exit(1)

def maybe_utf8(s, stream):
    if stream.isatty():
        # It will have an encoding, which Python will respect
        return s
    else:
        # It won't have an encoding, and Python will pick ASCII by default
        return s.encode('utf-8')

class Management:
    def __init__(self, options, args):
        self.options = options
        self.args = args

    def get(self, path):
        return self.http("GET", "/api%s" % path, "")

    def put(self, path, body):
        return self.http("PUT", "/api%s" % path, body)

    def post(self, path, body):
        return self.http("POST", "/api%s" % path, body)

    def delete(self, path):
        return self.http("DELETE", "/api%s" % path, "")

    def http(self, method, path, body):
        if self.options.ssl:
            conn = httplib.HTTPSConnection(self.options.hostname,
                                           self.options.port,
                                           self.options.ssl_key_file,
                                           self.options.ssl_cert_file)
        else:
            conn = httplib.HTTPConnection(self.options.hostname,
                                          self.options.port)
        headers = {"Authorization":
                       "Basic " + base64.b64encode(self.options.username + ":" +
                                                   self.options.password)}
        if body != "":
            headers["Content-Type"] = "application/json"
        try:
            conn.request(method, path, body, headers)
        except socket.error, e:
            die("Could not connect: {0}".format(e))
        resp = conn.getresponse()
        if resp.status == 400:
            die(json.loads(resp.read())['reason'])
        if resp.status == 401:
            die("Access refused: {0}".format(path))
        if resp.status == 404:
            die("Not found: {0}".format(path))
        if resp.status == 301:
            url = urlparse.urlparse(resp.getheader('location'))
            [host, port] = url.netloc.split(':')
            self.options.hostname = host
            self.options.port = int(port)
            return self.http(method, url.path + '?' + url.query, body)
        if resp.status < 200 or resp.status > 400:
            raise Exception("Received %d %s for path %s\n%s"
                            % (resp.status, resp.reason, path, resp.read()))
        return resp.read()

    def verbose(self, string):
        if self.options.verbose:
            output(string)

    def get_arg(self):
        assert_usage(len(self.args) == 1, 'Exactly one argument required')
        return self.args[0]

    def use_cols(self):
        # Deliberately do not cast to int here; we only care about the
        # default, not explicit setting.
        return self.options.depth == 1 and not 'json' in self.options.format

    def invoke_help(self):
        if len(self.args) == 0:
            parser.print_help()
        else:
            help_cmd = self.get_arg()
            if help_cmd == 'subcommands':
                usage = subcommands_usage()
            elif help_cmd == 'config':
                usage = config_usage()
            else:
                assert_usage(False, """help topic must be one of:
  subcommands
  config""")
            print usage
        exit(0)

    def invoke_publish(self):
        (uri, upload) = self.parse_args(self.args, EXTRA_VERBS['publish'])
        if not 'payload' in upload:
            data = sys.stdin.read()
            upload['payload'] = base64.b64encode(data)
            upload['payload_encoding'] = 'base64'
        resp = json.loads(self.post(uri, json.dumps(upload)))
        if resp['routed']:
            self.verbose("Message published")
        else:
            self.verbose("Message published but NOT routed")