#!/usr/bin/python
#
# Dump a list of plugins
#

import optparse
import pscheduler

pscheduler.set_graceful_exit()

#
# Gargle the arguments
#

class VerbatimParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog

opt_parser = VerbatimParser(
    usage="Usage: %prog [options] tests|tools|archivers|contexts",
    epilog="""
Example:

  plugins tools
      List the tool plugins on the local system

  plugins --host ps.example.org tests
      List the test plugins on ps.example.org
"""
    )
opt_parser.disable_interspersed_args()

opt_parser.add_option("--bind",
                      help="Make the request from the provided address",
                      default=None,
                      action="store", type="string",
                      dest="bind")
opt_parser.add_option("--host",
                      help="Query the specified host",
                      default=None,
                      action="store", type="string",
                      dest="host")

(options, remaining_args) = opt_parser.parse_args()

if len(remaining_args) != 1:
    opt_parser.print_usage()
    pscheduler.fail()

plugin = remaining_args[0]

if plugin not in ["tests", "tools", "archivers", "contexts"]:
    opt_parser.print_usage()
    pscheduler.fail()


#
# Fetch the list
#

url = pscheduler.api_url(options.host, path=plugin)

status, result = pscheduler.url_get(url,
                                    params={"expanded": True},
                                    bind=options.bind,
                                    throw=False)

if status == 400:
    pscheduler.fail("%s: %s" % (host, result))
elif status in [202, 204, 205, 206, 207, 208, 226,
                300, 301, 302, 303, 304, 205, 306, 307, 308] \
    or ((status >= 400) and (status <= 499)):
    pscheduler.fail("%s is not running pScheduler" % (options.host))
elif status != 200:
    pscheduler.fail("%s returned status %d: %s" % (host, status, result))


#
# Dump the results
#

print "Installed %s on %s:" % (
    plugin,
    options.host if options.host is not None else "this system"
    )


for item in result:
    print"\n\n%s Version %s" % (
        item["name"],
        item["version"]
    )
    print pscheduler.prefixed_wrap("  ", item["description"], indent=2)

    # Handle type-specific attributes

    if plugin == "tests":
        print
        print "  Scheduling: %s" % (item["scheduling-class"].title())
    if plugin == "tools":
        print
        runs = sorted(item["tests"])
        print "  Runs tests: %s" % ( (", ".join(runs)) if runs else "None" )
        print "  Preference: %d" % item["preference"]

    print
    print "  Maintainer: %s" % item["maintainer"]["name"]
    print "  Email:      %s" % item["maintainer"]["email"]
    print "  Website:    %s" % item["maintainer"]["href"]

pscheduler.succeed()
