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

import datetime
import sys

import pscheduler

# Highest this tool supports
MAX_SCHEMA = 2

try:
    json = pscheduler.json_load(exit_on_error=True, max_schema=MAX_SCHEMA);
except ValueError as ex:
    pscheduler.succeed_json({
        "can-run": False,
        "reasons": [ str(ex) ]
    })

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, MAX_SCHEMA)
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 = []

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

# Other than algorithm, traceroute can handle the entire spec.  The
# restriction is that first-ttl must be within max-ttl.

try:
    first_ttl = spec['first-ttl']
    max_ttl = spec['max-ttl'] if 'max-ttl' in spec else 30
    if first_ttl > max_ttl:
        errors.append("First TTL must be less than the number of hops.")
except KeyError:
    pass  # None is okay

# TODO:  Remove this when we can do multiples.
try:
    queries = spec['queries']
    if queries != 1:
        errors.append("Cannot handle more than one query per hop")
except KeyError:
    pass


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

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

pscheduler.succeed_json(result)
