#!/usr/bin/env python3
#
# Determine the duration of a specified test.
#

import datetime
import sys

import pscheduler

spec = pscheduler.json_load(exit_on_error=True);

# TODO: Make sure the type is one we like
# TODO: Validate the spec

total = datetime.timedelta()

#
# Tool run time
#

# TODO: Don't include this time if the destination is already an IP
# TODO: Get the timeout from the DNS module
total = datetime.timedelta(seconds=2)

try:
    count = int(spec['count'])
except KeyError:
    count = 5

try:
    interval = pscheduler.iso8601_as_timedelta(spec['interval'])
except KeyError:
    interval = datetime.timedelta(seconds=1)

if count > 1:
    # We do one less because there's no wait interval after the last
    # packet other than the timeout.
    total += (count - 1) * interval

# Stick one timeout on the end, which comes from waiting for the last packet.

try:
    timeout = pscheduler.iso8601_as_timedelta(spec['timeout'])
except KeyError:
    timeout = datetime.timedelta(seconds=2)
total += timeout


# A deadline overrides everything if it's shorter than what we've
# calculated so far.

try:
    deadline = pscheduler.iso8601_as_timedelta(spec['deadline'])
    if deadline < total:
        total = deadline
except KeyError:
    pass  # No deadline is just fine.


#
# DNS Resolution
#

try:
    hostnames = spec['hostnames']
except KeyError:
    hostnames = True

# Some time for DNS, which will be done in parallel.
# TODO: Should probably ask the DNS module for the timeout.
if hostnames:
    total += datetime.timedelta(seconds=2)


#
# Slop
#

total += datetime.timedelta(seconds=1)

pscheduler.succeed_json({
        "duration": pscheduler.timedelta_as_iso8601(total)
})
