# plugs/dig.py
#
#
#

""" do the dig """

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import gozerpopen
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp

plughelp.add('dig', 'run a dig command')

def handle_dig(bot, ievent):
    """ dig <domain> <querytype> .. show dig response """
    if len(ievent.args) < 2:
        ievent.missing('<domain> <querytype>')
        return
    args = []
    userargs = []
    args.append('dig')
    userargs.append(ievent.args[0])
    userargs.append(ievent.args[1])
    try:
        proces = gozerpopen(args, userargs)
    except Exception, ex:
        ievent.reply('error running popen: %s' % str(ex))
        return
    data = proces.fromchild.readlines()
    returncode = proces.close()
    if returncode != 0:
        ievent.reply('error running dig')
        return
    result = []
    doit = 0
    for i in data:
        # search output for answer section
        if i.find('ANSWER SECTION') != -1:
            doit = 1
            continue
        i = i.strip()
        if i and doit:
            i = i.replace('\t',' ')
            result.append(i)
            if i.find(';;') != -1:
                doit = 0
    if result:
        ievent.reply(' ==> '.join(result))
    else:
        ievent.reply('no result')

cmnds.add('dig', handle_dig, 'USER')
examples.add('dig', 'dig <hostname> <querytype> .. show dig output', \
'dig gozerbot.org A')
