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

import datetime
import sys
import socket
from contextlib import closing

import pscheduler

logger = pscheduler.Log(prefix='tool-bwctltracepath', quiet=True)

json = pscheduler.json_load(exit_on_error=True);


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 = []

unsupported_options = [ 'algorithm', 'as', 'dest-port', 'fragment', 'probe-type', 'queries', 'sendwait', 'wait', 'sendwait', 'hops', 'first-ttl' ]
for unsupported_option in unsupported_options:
    if spec.has_key(unsupported_option):
        errors.append("BWCTL does not support %s" % unsupported_option)


source = spec.get("source", "localhost")

# This digs up everything we can on the hosts involved in a
# time-predictable way.
has = pscheduler.api_has_services([source], timeout=3)

if has[source]["pscheduler"]:
    errors.append("Source has pscheduler, no need for BWCTL")

if not has[source]["bwctl"]:
    logger.debug("No BWCTL at source")
    errors.append("No BWCTL on %s" % source)

logger.debug("can-run succeeded") 


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

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

pscheduler.succeed_json(result)

