#!/usr/bin/env python3
#
# Checker for 'trace' task limits
#

import pscheduler

from validate import spec_is_valid
from validate import limit_is_valid

#
# Load and validate everything
#

try:
    json = pscheduler.json_load(max_schema=1)
except ValueError as ex:
    pscheduler.fail("Invalid JSON %s" % str(ex))

spec = json["spec"]
limit = json["limit"]


#
# Evaluate everything
#

#
# Handle source, dest and endpoint limits
#
errors = pscheduler.check_endpoint_limits(limit, spec)

#
# Handle numeric ranges
#
numeric_ranges = [
    ("dest-port", "Destination port"),
    ("first-ttl", "First time to live"),
    ("hops", "Number of hops"),
    ("length", "Length"),
    ("queries", "Number of queries"),
]
for nr in numeric_ranges:
    errors += pscheduler.check_numeric_limit(limit, spec, nr[0], description=nr[1])

#
# Handle boolean fields
#
booleans = [
    ("as", "AS resolution"),
    ("hostnames", "Hostname resolution"),
    ("fragment", "Fragmentation"),
]
for b in booleans:
    errors += pscheduler.check_boolean_limit(limit, spec, b[0], description=b[1])

#
# Handle duration fields
#
durations = [
    ("send-wait", "Send wait"),
    ("wait", "Wait"),
]
for d in durations:
    errors += pscheduler.check_duration_limit(limit, spec, d[0], description=d[1])


#
# Restrict ip-version
#
errors += pscheduler.check_enum_limit(limit, spec, 'ip-version', description='IP Version')

#
# Handle ip-tos (numeric list)
#
errors += pscheduler.check_numeric_list_limit(limit, spec, 'ip-tos', description="IP TOS")

#
# Handle string limits
#
string_limits = [
    ("algorithm", "Algorithm"),
    ("probe-type", "Probe type"),
]
for s in string_limits:
    errors += pscheduler.check_string_limit(limit, spec, s[0], description=s[1])

#
# Finish up
#

result = { "passes": not errors }

if errors:
    result["errors"] = errors

pscheduler.succeed_json(result)
