#!/usr/bin/env python
#
#

""" exec gozerbot commands from the command line. """

__copyright__ = 'this file is in the public domain'

# ==============
# IMPORT SECTION

# gozerbot imports

def showexceptions():
    teller = 0

    for ex in exceptionlist:
        teller += 1
        print "EXCEPTION NR %s" % teller
        print ex

    print "total of %s exceptions" % teller
    return exceptionlist

import sys, os, time
starttime = time.time()
sys.path.insert(0, os.getcwd())

from gozerbot.tests import tests
from gozerbot.utils.exception import handle_exception, exceptionlist
from gozerbot.eventbase import EventBase
from gozerbot.botbase import BotBase
from gozerbot.users import users
from gozerbot.exit import globalshutdown
from gozerbot.eventhandler import mainhandler
from gozerbot.utils.log import enable_logging, disable_logging
from gozerbot.utils.generic import waitforqueue
from gozerbot.threads.thr import start_new_thread
from gozerbot.periodical import periodical
from gozerbot.plugins import plugins
from gozerbot.database.alchemy import startmaindb
from gozerbot.persist.persist import Persist
from gozerbot.commands import cmnds

import gozerbot

# basic imports
from optparse import OptionParser
import asyncore, time, Queue

# END IMPORT
# ==========

parser = OptionParser(usage='usage: %prog [options]', version='%prog ' + gozerbot.__version__)
parser.add_option('-l', '--loglevel', type='string', default=False, dest='loglevel',
                  help="loglevel")
parser.add_option('-c', '--chan', type='string', default=False, dest='channel',
                  help="channel to use")
parser.add_option('-n', '--nick', type='string', default=False, dest='nick',
                  help="nick to use")
parser.add_option('-u', '--userhost', type='string', default=False, dest='userhost',
                  help="userhost to use")
parser.add_option('-p', '--plugin', type='string', default=False, dest='plugin',
                  help="plugin to load")
parser.add_option('-s', '--sleep', type='string', default=False, dest='sleep',
                  help="sleeptime to set as event option")
parser.add_option('-e', '--exceptions', action="store_true", default=False, dest='exceptions',
                  help="show exceptions list after finishing the command")
parser.add_option('-w', '--wait', type="string", default=False, dest='wait',
                  help="nr of seconds to wait for completion")
parser.add_option('-a', '--all', action="store_true", default=False, dest='all',
                  help="load all plugins")
parser.add_option('-v', '--verbose', action="store_true", default=False, dest='verbose',
                  help="be verbose")

# skip part after //
index = 0
for i in sys.argv:
    if '//' not in i:
        index += 1
    else:
        break
    
cmndargs = sys.argv[1:index]
botargs = sys.argv[index+1:]

opts, args = parser.parse_args(cmndargs)
opts.args = args

v = opts.verbose

try:
    cmnd = args[0]
except IndexError:
    print "what command?"
    os._exit(0)

enable_logging(int(opts.loglevel) or 1000)
periodical.start()
startmaindb()

if v: print "GOZERBOT %s starting" % gozerbot.__version__
if v: print "registering core plugins"
plugins.regcore()
if v:print "looking for cmndtable ..."

cmndtable = Persist('cmndtable')

if cmndtable.data:
    if v: print "found"
else:
    cmndtable.data = {}
    print "initialising cmndtable ..."
    plugins.regplugins()

    for cmndname, c in cmnds.iteritems():
        cmndtable.data[cmndname] = c.plugname

    cmndtable.save()
    print "done"

try:
    plug = cmndtable.data[cmnd]
except KeyError:
    print "no %s command found" % cmnd
    os._exit(0)

try:
    plugins.regplugin('gozerplugs', plug)
except ImportError:
    try:
        plugins.regplugin('myplugs', plug)
    except ImportError:
        print "can't load the %s plugin" % plug

if opts.all:
    plugins.regplugins()

    for cmndname, cmnd in cmnds.iteritems():
        cmndtable.data[cmndname] = cmnd.plugname
    cmndtable.save()


if v: print "plugins loaded .. starting"
end = False

try:
    bot = BotBase('execbot', {'nick': opts.nick or 'exec'})
    event = EventBase()
    event.nick = opts.nick or 'exec'
    event.userhost = opts.userhost or 'exec@gozerbot'

    try:
        users.add(event.nick, [event.userhost,], ['USER', 'OPER'])
    except Exception, ex:
        pass

    event.txt = "!" + " ".join(args)

    if botargs:
         event.txt += ' ' + ' '.join(botargs)

    event.origtxt = event.txt
    event.bot = bot
    event.msg = True
    event.isdcc = True
    event.channel = opts.channel or "exec@gozerbot"
    q = Queue.Queue()
    event.queues.append(q)

    # GO !
    bot.domsg(event)

    start_new_thread(bot.serveforever, ())

    if opts.wait:
        resultnotused = waitforqueue(q, timeout=int(opts.wait))
    else:
        resultnotused = waitforqueue(q, 900)

    if opts.exceptions:
        showexceptions()

    if v: print "elapsed time: %s seconds" % (time.time() - starttime)
    sys.stdout.flush()
    time.sleep(0.01)
    os._exit(0)

except KeyboardInterrupt:
    showexceptions()
except Exception, ex:
    handle_exception()
    disable_logging()
    sys.stdout.flush()
    time.sleep(0.01)
    os._exit(1)
