#!/usr/bin/env python3
#
# Determine if this tool can run a test based on a test spec.
#

import datetime
import sys

import pscheduler

json = pscheduler.json_load(exit_on_error=True);

# TODO: Should be checking the package schema and the task spec schema.
# TODO: Should be validating.

try:
    if json['type'] != 'trace':
        pscheduler.succeed_json({
            "can-run": False,
            "reasons": [ "Unsupported test type" ]
        })
except KeyError:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [ "Missing test type" ]
    })


try:
    spec = json["spec"]
    pscheduler.json_check_schema(spec, 1)
except KeyError:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": ["Missing test specification"]
    })
except ValueError as ex:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [str(ex)]
    })


errors = []

def check_with_error(name, error):
    if name in spec:
        errors.append(error)


if 'algorithm' in spec:
    errors.append("Algorithm '%s' is not supported" % spec['algorithm'])


try:
    probe_type = spec['probe-type']
    if probe_type != 'udp':
        errors.append("Probe type '%s' is not supported" % probe_type)
except KeyError:
    pass  # None is okay, default behavior is UDP


try:
    length = spec['length']
    # Length must be in 28..sys.maxint
    if isinstance(length, int) and (length < 28 or length > sys.maxsize):
        errors.append("Cannot handle specified packet length")
except KeyError:
    pass


try:
    fragment = spec['fragment']
    if fragment != False:
        errors.append("Allowing fragmentation is not supported")
except KeyError:
    pass


check_with_error('first-ttl', "Cannot control first TTL")

try:
    hops = spec['hops']
    if hops > 255:
        errors.append("Cannot set more than 255 hops")
except KeyError:
    pass


try:
    queries = spec['queries']
    if queries != 1:
        errors.append("Cannot handle more than one query per hop")
except KeyError:
    pass



# hostnames is okay whether on, off or missing.

check_with_error('ip-tos', "Cannot control IP TOS")
check_with_error('wait', "Cannot control response wait time")
check_with_error('sendwait', "Cannot control delay between sends")


result = {
    "can-run": len(errors) == 0
}

if len(errors) > 0:
    result["reasons"] = errors

pscheduler.succeed_json(result)
