#!/usr/bin/python
#
# Participant list generator for 'rtt' test spec
#

import pscheduler
import sys

from validate import spec_is_valid

json = pscheduler.json_load(exit_on_error=True, max_schema=3)

null_reason = None

valid, message = spec_is_valid(json)

if not valid:
    pscheduler.fail(message)

######################################################################
# HACK: BWCTLBC
#Backward Compatibility Code: We can remove this once we drop BWCTL
#
# Check that both sides have pScheduler and do the following:
# * if source has pscheduler, proceed as normal (i.e. use source as only participant)
# * otherwise if dest has pscheduler use that instead
# * otherwise fail the test if no one has pscheduler


participants = []
source = json.get("source-node", json.get("source", None))
if source is None:
    null_reason = "No source specified"

# Note that because this is a one-participant test, there is no node
# we talk to at the destination end.
if "dest" in json:
    destination = json["dest"]
else:
     pscheduler.fail("Missing required field dest")
    

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

if has[source]["pscheduler"]:
    participants = [ source ]
elif has[destination]["pscheduler"]:
    participants = [ destination ]
else:
    #if backward compatibility hacks failed, proceed normally
    participants = [ source ]
######################################################################

result = { "participants": participants }
if null_reason is not None:
    result["null-reason"] = null_reason

pscheduler.succeed_json(result)
