#!/usr/bin/env python
#
#

""" start the bot from standalone directory """

__copyright__ = 'this file is in the public domain'

import sys, os, socket

if os.getuid() == 0:
    print "don't run the bot as root"
    os._exit(1)

vi = sys.version_info

if vi[0] < 2 or (vi[0] == 2 and vi[1] < 4):
    print "i need at least python version >= 2.4"
    os._exit(1)

for i in sys.argv:
    if os.path.isdir(i):
        os.chdir(i)
        print 'changed dir to %s' % i
        break

sys.path.insert(0, os.getcwd())
sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), 'myplugs', 'addons')))

from optparse import OptionParser

parser = OptionParser(usage='usage: %prog [options]', version='%prog 0.8.1')

parser.add_option('', '-a', action='store_true', default=False, dest='doascii',
                  help="Use ASCII as the default encoding instead of UTF-8")
parser.add_option('', '-b', action='store_true', default=False, dest='dobackup',
                  help="Do Backup")
parser.add_option('', '-u', action='store_false', default=True, dest='doumode',
                  help="Check permissions on the gozerdata folder")
parser.add_option('', '-r', type='string', default=False, dest='doresume', 
                  metavar='PATH', 
                  help="Resume the bot from the folder specified")

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

if not opts.doascii:
    reload(sys)
    sys.setdefaultencoding('utf-8')

sys.setcheckinterval(50)
socket.setdefaulttimeout(30)

from gozerbot.generic import handle_exception

try:
    from gozerbot.config import config, writeconfig, writeloadlist
    from gozerbot.datadir import makedirs
    from gozerbot.generic import enable_logging
    makedirs()
    writeconfig()
    writeloadlist()
    config.load()
    enable_logging()
except Exception, ex:
    handle_exception()
    os._exit(1)

try:
    from gozerbot.generic import rlog, handle_exception, checkpermissions
    from gozerbot.bot import Bot
    from gozerbot.fleet import fleet
    from gozerbot.plugins import plugins
    from gozerbot.eventhandler import mainhandler
    from gozerbot.users import users
    from gozerbot.thr import start_new_thread
    from gozerbot.partyline import partyline
    from gozerbot.exit import globalshutdown
except Exception, ex:
    handle_exception()
    os._exit(1)

import time, signal, gc, types

# enable garbage collection
gc.enable()

# provide sigterm support
def dostop(a, b):
    """ sig handler """
    globalshutdown()

signal.signal(signal.SIGTERM, dostop)


rlog(10, 'GOZERBOT', 'starting %s' % config['version'])
rlog(5, 'gozerbot', 'default encoding is %s' % sys.getdefaultencoding())

if opts.doumode:
    umask = config['umask']
    if not umask:
        checkpermissions('gozerdata', 0700)
    else:
        checkpermissions('gozerdata', umask)

# write pid to pidfile
k = open('gozerbot.pid','w')
k.write(str(os.getpid()))
k.close()

# see if owner already has a user account if not merge otherwise add
owner = []

if config['jabberenable']:
    if type(config['jabberowner']) != types.ListType:
        owner.append(config['jabberowner'])
    else:
        owner = config['jabberowner']

if type(config['owneruserhost']) != types.ListType:
    owner.append(config['owneruserhost'])
else:
    owner += config['owneruserhost']

try:
    for i in owner:
        username = users.getname(i)
        if not username:
            if not users.merge('owner', i):
                users.add('owner', [i, ], perms = ['USER', 'OPER'])
except Exception, ex:
    print str(ex)
    os._exit(1)

# register plugins
start_new_thread(plugins.regplugins, ())

# create the bot and connect
if config['jabberenable']:
    try:
        from gozerbot.jabberbot import Jabberbot
    except ImportError:
        handle_exception()
        os._exit(1)
    bot = Jabberbot('jabbermain', config['jabberowner'])
    bot.host = config['jabberhost']
    bot.user = config['jabberuser']
    bot.password = config['jabberpass']
    bot.port = 5222
    # add to fleet
    fleet.addbot(bot)

if not config['ircdisable']:
    bot = Bot('main', config['owneruserhost'])
    bot.nick = config['nick'] or 'gb1'
    bot.server = config['server'] or 'localhost'
    bot.port = config['port'] or 6667
    bot.password = config['password'] or ""
    bot.ipv6 = config['ipv6'] or 0
    bot.ssl = config['ssl'] or 0
    # add to fleet
    fleet.addbot(bot)

if opts.doresume and os.path.isfile(opts.doresume):
    fleet.resume(opts.doresume)
    fleet.startok.wait()
    partyline.resume(opts.doresume)
    os.unlink(opts.doresume) # bye
else:
    fleet.start()

while 1:
    try:
        time.sleep(1)
        mainhandler.handle_one()
    except KeyboardInterrupt:
        globalshutdown()
        os._exit(0)
    except Exception, ex:
        handle_exception()
        globalshutdown()
        os._exit(1)
