#!/usr/bin/env python3

#
# Convert command-line options to a test specification for http test
#

import re
import optparse
import pscheduler
import sys

if len(sys.argv) > 1:

    # Args are on the command line
    args = sys.argv[1:]

else:

    # Args are in a JSON array on stdin
    json_args = pscheduler.json_load(exit_on_error=True)
    args = []

    if not isinstance(json_args,list):
        pscheduler.fail("Invalid JSON for this operation")
    for arg in json_args:
        if not ( isinstance(arg, str)
                 or isinstance(arg, int)
                 or isinstance(arg, float) ):
            pscheduler.fail("Invalid JSON for this operation")
    args = [ str(arg) for arg in json_args ]


# Gargle the arguments

opt_parser = pscheduler.FailingOptionParser(epilog=
    """
      Example:
      task http --url http://umich.edu --timeout PT10S
      task http --url http://google.com --parse search
      """
)


opt_parser.add_option("--url",
                      help="URL to query",
                      action="store", type="string",
                      dest="url")

opt_parser.add_option("--header",
                      help="HTTP header for request, format 'HeaderName: Value'.  May be repeated.",
                      action="append", type="string",
                      dest="headers")

opt_parser.add_option("--parse",
                      help="String to parse for",
                      action="store", type="string",
                      dest="parse")

opt_parser.add_option("--host",
                      help="Host to run the test",
                      action="store", type="string",
                      dest="host")

opt_parser.add_option("--host-node",
                      help="Host to run the test",
                      action="store", type="string",
                      dest="host_node")

opt_parser.add_option("--ip-version",
                      help="Specificy which IP version to use, 4 or 6",
                      action="store", type="int",
                      dest="ip_version")

opt_parser.add_option("--always-succeed",
                      help="Treat HTTP failures as successes, regardless of response code",
                      action="store_true",
                      dest="always_succeed")

opt_parser.add_option("--keep-content",
                      help="Amount of content to keep in bytes; default none, 0 for all, SI units supported",
                      type="string",
                      action="store",
                      dest="keep_content")

opt_parser.add_option("--timeout",
                      help="Timeout for each query attempt",
                      action="store", type="string",
                      dest="timeout")

(options, remaining_args) = opt_parser.parse_args(args)

if len(remaining_args) != 0:
    pscheduler.fail("Unusable arguments: %s" % " ".join(remaining_args))

schema = pscheduler.HighInteger(1)
result = { }

if options.host is not None:
    result['host'] = options.host
if options.host_node is not None:
    result['host-node'] = options.host_node
if options.ip_version is not None:
    result["ip-version"] = options.ip_version
    schema.set(3)

if options.url is not None:
    result['url'] = options.url

if options.headers is not None:
    result['headers'] = {
        key.strip(): value.strip()
        for (key, value) in [item.split(':') for item in options.headers]
    }
    schema.set(4)

if options.parse is not None:
    result['parse'] = options.parse
if options.timeout is not None:
    result['timeout'] = options.timeout
if options.always_succeed is not None:
    schema.set(2)
    result['always-succeed'] = options.always_succeed

if options.keep_content is not None:
    try:
        result['keep-content'] = pscheduler.si_as_number(options.keep_content)
    except ValueError as ex:
        pscheduler.fail("Invalid value \"%s\" for keep-content: %s" % (options.bandwidth, ex))
    schema.set(2)

result['schema'] = schema.value()

pscheduler.succeed_json(result)
