#!/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 idleex --duration PT1M15S
      Do nothing locally for one minute and 15 seconds

  task idleex --duration PT20S --host ps2.example.org
      Make ps2.example.org be idle for 20 seconds

  task idleex --duration PT20S --starting-comment "Let's get lazy."
      Emit a custom comment before idling

  task idleex --duration PT20S --parting-comment "I got nothing done."
      Emit a custom comment after idling

"""
                                            )


opt_parser.add_option("-d", "--duration",
                      help="Idle duration (ISO8601)",
                      action="store", type="string",
                      dest="duration")


# The short version is capitalized because -h is for help.
opt_parser.add_option("-H", "--host",
                      help="Host which should be idle",
                      action="store", type="string",
                      dest="host")

opt_parser.add_option("--host-node",
                      help="pScheduler node",
                      action="store", type="string",
                      dest="host_node")

opt_parser.add_option("-s", "--starting-comment",
                      help="Starting comment",
                      action="store", type="string",
                      dest="starting_comment")

opt_parser.add_option("-p", "--parting-comment",
                      help="Parting comment",
                      action="store", type="string",
                      dest="parting_comment")

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

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


result = { 'schema': 1 }

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

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

if options.parting_comment is not None:
   result['parting-comment'] = options.parting_comment

pscheduler.succeed_json(result)


