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

import pscheduler
import sys

from validate import spec_is_valid

json = pscheduler.json_load(exit_on_error=True)

null_reason = None

valid, message = spec_is_valid(json)

if not valid:
    pscheduler.fail(message)

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


######################################################################
# 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 = []
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 source is None or has[source]["pscheduler"]:
    participants = [ source ]
elif has[destination]["pscheduler"]:
    participants = [ destination ]
else:
    pscheduler.fail("Neither the source nor destination is running pScheduler.")
######################################################################

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

pscheduler.succeed_json(result)
