#!/usr/bin/env python3
#
# Ping another pScheduler host to see if it responds
#

import optparse
import pscheduler

pscheduler.set_graceful_exit()

#
# Gargle the arguments
#


class VerbatimParser(optparse.OptionParser):
    def format_epilog(self, formatter):
        return self.epilog

opt_parser = VerbatimParser(
    usage="Usage: %prog [ HOST ]",
    epilog=
"""
Example:

  ping
      Check on the local host

  ping perfsonar6.example.org
      Check on the host at perfsonar6.example.org
"""
    )
opt_parser.disable_interspersed_args()

opt_parser.add_option("--bind",
                      help="Make the request from the provided address",
                      default=None,
                      action="store", type="string",
                      dest="bind")
opt_parser.add_option("--quiet", "-q",
                      help="Run without any output",
                      action="store_true", default=False,
                      dest="quiet")
opt_parser.add_option("--timeout", "-W",
                      help="How long to wait for the server to respond, in seconds (default 5)",
                      default=5,
                      action="store", type="int",
                      dest="timeout")


(options, remaining_args) = opt_parser.parse_args()

if len(remaining_args) > 1:
    opt_parser.print_usage()
    pscheduler.fail()

if options.timeout <= 0:
    pscheduler.fail("Timeout must be >= 0")

try:
    host = remaining_args[0]
    host_display = host
except IndexError:
    host = None
    host_display = pscheduler.api_local_host()

up, reason = pscheduler.api_ping(host, timeout=options.timeout,
                                 bind=options.bind)

message = "%s: %s" % (host_display, reason)

if up:
    pscheduler.succeed(message)

pscheduler.fail(message)
