#!/usr/bin/python

# Copyright 2011 Peter Palfrader
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import datetime
import socket
import optparse
import sys

parser = optparse.OptionParser()
parser.set_usage("%prog <hostname> [<hostname> ..]")
parser.add_option("-t", "--timeout", dest="timeout", metavar="TIMEOUT",
  type="int", default=500,
  help="Resolve timeout in msecs [500].")
(options, args) = parser.parse_args()

if len(args) == 0:
    parser.print_help()
    sys.exit(4)

def check(hostname):
    now = datetime.datetime.now()
    try:
        socket.gethostbyname(hostname)
    except:
        return None
    then = datetime.datetime.now()

    td = then - now
    msecs = td.microseconds/1000 + (td.seconds + td.days * 24 * 3600) * 1000
    return msecs

msg = []
ret = 0
oklist = []
slowlist = []
faillist = []
for hostname in args:
    time = check(hostname)
    if time is None:
        faillist.append(hostname)
        ret = 2
    elif time > options.timeout:
        slowlist.append(hostname)
        ret = max(ret, 1)
    else:
        oklist.append(hostname)

if len(faillist) > 0: msg.append("FAILED: %s"%(', '.join(faillist)))
if len(slowlist) > 0: msg.append("SLOW: %s"%(', '.join(slowlist)))
if len(oklist) > 0: msg.append("OK: %s"%(', '.join(oklist)))

print '; '.join(msg)
sys.exit(ret)

# vim:set et:
# vim:set ts=4:
# vim:set shiftwidth=4:
