#!/usr/bin/env python3
#
# 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] test[s]|tool[s]|archiver[s]|context[s]",
    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=pscheduler.api_local_host(),
                      action="store", type="string",
                      dest="host")
opt_parser.add_option("--verbose", "-v",
                      help="Dump long-form information about the plugins",
                      default=False,
                      action="store_true",
                      dest="verbose")

(options, remaining_args) = opt_parser.parse_args()

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

plugin = remaining_args[0]

if not plugin.endswith("s"):
    plugin += "s"

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


verbose = options.verbose


#
# 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" % (options.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" % (options.host, status, result))


#
# Dump the results
#

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


for item in result:

    if not verbose:
        print('{0:<20} {1}'.format(item["name"], item["description"]))
        continue

    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()
