# plugs/ipcalc.py
#
#
#

""" uses the ipcalc program """

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import handle_exception, gozerpopen
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
import re, socket

plughelp.add('ipcalc', 'use the ipcalc program (if installed)')

def handle_ipcalc(bot, ievent):
    """ ipcalc <ip> .. show ipcalc output """
    if len(ievent.args) != 1:
        ievent.missing('<ip>')
        return
    args = []
    userargs = []
    args.append('ipcalc')
    args.append('-b')
    userargs.append(ievent.args[0])
    proces = gozerpopen(args, userargs)
    data = proces.fromchild.readlines()
    result = proces.close()
    if result:
        ievent.reply('error running ipcalc')
        return
    if not data:
        ievent.reply("there is no ipcalc installed on this system")
        return
    if data[0].find('INVALID') != -1:
        ievent.reply("%s is not valid ipcalc input" % ievent.args[0])
        return
    result = []
    hosts = []
    for i in data:
        tmp = re.sub('\s+', ' ', i)
        i = i.strip()
        if i.startswith('Address'):
            hosts.append(i[8:])
        result.append(tmp.strip())
    if result:
        ievent.reply(' '.join(result))
        for i in hosts:
             i = i.strip()
             try:
                 hostname = socket.gethostbyaddr(i)[0]
             except:
                 continue
             ievent.reply("%s is %s" % (i, hostname))
    else:
        ievent.reply('no result')

cmnds.add('ipcalc', handle_ipcalc, 'USER')
examples.add('ipcalc', 'ipcalc <ip> .. show ipcalc output', 'ipcalc 127.0.0.1')
