#!/usr/bin/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())

import getopt

doascii = False
dobackup = True
doumode = True

try:
    (options, rest) = getopt.getopt(sys.argv[1:], 'abu')
    for i, j in options:
        if i == '-a':
            doascii = True
        if i == '-b':
            dobackup = True
        if i == '-u':
            doumode = False
except getopt.GetoptError, ex:
    print str(ex)

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


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

from gozerbot.generic import rlog, handle_exception, enable_logging, \
checkpermissions
from gozerbot.config import config, writeconfig
from gozerbot.bot import Bot
from gozerbot.fleet import fleet
from gozerbot.plugins import plugins
from gozerbot.backup import backup
from gozerbot.eventhandler import mainhandler
from gozerbot.users import users
from gozerbot.thr import start_new_thread
from gozerbot.datadir import makedirs
from gozerbot.exit import globalshutdown
import time, signal

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

signal.signal(signal.SIGTERM, dostop)

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

if 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 = config['owneruserhost']
username = users.getname(owner)
if not username:
    if not users.merge('owner', owner):
        users.add('owner', [owner, ], perms = ['USER', 'OPER'])

# startup backup thread
if dobackup:
    start_new_thread(backup, ())

# create the bot and connect
rlog(10, 'gozerbot', 'loading plugins')
plugins.regplugins()
if config['jabberenable']:
    from gozerbot.jabberbot import Jabberbot
    bot = Jabberbot('jabbermain')
    bot.host = config['jabberhost']
    bot.user = config['jabberuser']
    bot.password = config['jabberpass']
    bot.port = 5222
else:
    bot = Bot(config['owneruserhost'])
    bot.nick = config['nick'] or 'gb1'
    bot.server = config['server'] or 'localhost'
    bot.port = config['port'] or 6667
    bot.password = config['password']
    bot.ipv6 = config['ipv6']

# add to fleet
fleet.addbot(bot)
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(0)
