#!/usr/bin/python
#
# 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'] != 'rtt':
        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)]
    })


# This tool runs the entire version 1 schema.

errors = []

# HACK: BWCTLBC
#prevent reverse tests where remote side does not have pscheduler from being allowed
#can probably remove if we ever drop bwctlping support
source = spec.get("source-node", spec.get("source", None))
if source and not pscheduler.api_has_pscheduler(source):
    errors.append("Source must have pscheduler")
    
try:
    ip_version = spec['ip-version']
except KeyError:
    ip_version = 4


if 'flow-label' in spec and ip_version != 6:
    errors.append("Cannot apply flow labels except with IPv6")


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

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

pscheduler.succeed_json(result)
