# ping plugin, depends on the ping binary

import os, re, popen2
from gozerbot.commands import cmnds

re_ok = re.compile('[^-_\.a-zA-Z0-9]')

def handle_ping(bot, ievent):
    if not ievent.args:
        ievent.missing('<host>')
        return
    host = ievent.args[0]
    if re_ok.match(host) or host[0] in '-_.':
        ievent.reply('invalid hostname or ip')
        return
    ping = None
    for p in os.environ['PATH'].split(':'):
        if not ping and os.path.isfile('%s/%s' % (p, ievent.command)):
            ping = '%s/%s' % (p, ievent.command)
    if not ping:
        ievent.reply('no %s installed' % ievent.command)
	return

    # now without path, caused errors in Linux
    # update: added /usr/bin/env
    ievent.reply('running ping on %s' % host)
    (r,w,e) = popen2.popen3('%s -c 3 %s' % (ping, host))
    a = e.read()
    e.close()
    if len(a):
        ievent.reply('error: %s' % ', '.join(a.split('\n')).rstrip(', ').replace('ping: ', ''))
        r.close()
        w.close()
    else:
        h = r.read()
        r.close()
        w.close()
        report = h.splitlines()[-1]
        ievent.reply(report)

cmnds.add('ping', handle_ping, 'USER')
cmnds.add('ping6', handle_ping, 'USER')

