#!/usr/bin/env python3
#
# Convert comamnd-line options to a test specification

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=
'''Examples:

  task noop --data '{ "foo": 123, "bar": false }'
      Pass data through.

  task noop --fail 0.5 --data '{ "foo": 123, "bar": false }'
      Pass data through, but fail half the time.
'''
                                            )


opt_parser.add_option('--data',
                      help='JSON data (defaults to null)',
                      action='store', type='string',
                      dest='data')

opt_parser.add_option('--host',
                      help='Host for test',
                      action='store', type='string',
                      dest='host')

opt_parser.add_option('--host-node',
                      help='Host node for test',
                      action='store', type='string',
                      dest='host_node')

opt_parser.add_option("-f", "--fail",
                      help="Probability of forced failure",
                      action="store", type="float",
                      dest="fail")



(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.data is not None:
    try:
        result['data'] = pscheduler.json_load(options.data)
    except ValueError:
        pscheduler.fail('Invalid data (must be JSON)')

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.fail is not None:
   result['fail'] = options.fail

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

pscheduler.succeed_json(result)
