"""
dr.botzo - a pluggable IRC bot written in Python
Copyright (C) 2010  Brian S. Stephan

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import django
from django.conf import settings

from ConfigParser import ConfigParser, NoSectionError, NoOptionError
import logging
import logging.config
import os
import sys

import MySQLdb as mdb

import DrBotIRC

# gross hack to get to django
sys.path.insert(0, '../dr_botzo')
django.setup()

config_file = 'dr.botzo.cfg'
# check argv
if len(sys.argv) == 2:
    config_file = sys.argv[1]

# read config file
config = ConfigParser({'debug': 'false'})
config.read(os.path.expanduser(config_file))

logging.config.fileConfig('logging.cfg')
log = logging.getLogger('drbotzo')

try:
    dbhost = config.get('dr.botzo', 'dbhost')
    dbuser = config.get('dr.botzo', 'dbuser')
    dbpass = config.get('dr.botzo', 'dbpass')
    dbname = config.get('dr.botzo', 'dbname')
    db = mdb.connect(dbhost, dbuser, dbpass, dbname, charset='utf8',
                     use_unicode=True)
    try:
        cur = db.cursor()
        # need to create the drbotzo_modules table if it doesn't exist
        query = """
            SELECT COUNT(*) FROM information_schema.tables
              WHERE table_schema = %s
                AND table_name = %s
        """
        cur.execute(query, (dbname, 'drbotzo_modules'))
        row = cur.fetchone()
        if row[0] == 0:
            query = """
                CREATE TABLE IF NOT EXISTS drbotzo_modules (
                  module VARCHAR(64) PRIMARY KEY,
                  version INTEGER
                ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin
            """
            cur.execute(query)
            db.commit()
    finally: cur.close()
except NoOptionError as e:
    sys.exit("Aborted due to error with necessary configuration: "
             "{0:s}".format(str(e)))

# get some optional parameters
use_ssl = False
try:
    use_ssl = config.getboolean('dr.botzo', 'ssl')
except NoOptionError:
    pass
if use_ssl:
    log.info("SSL support enabled")
else:
    log.debug("SSL not requested")

use_ipv6 = False
try:
    use_ipv6 = config.getboolean('dr.botzo', 'ipv6')
except NoOptionError:
    pass
if use_ipv6:
    log.info("IPv6 support enabled")
else:
    log.debug("IPv6 not requested")

# start up the IRC bot

# create IRC and server objects and connect
irc = DrBotIRC.DrBotIRC(config)
server = irc.server().connect(settings.IRC_SERVER,
                              settings.IRC_PORT,
                              settings.IRC_NICK,
                              settings.IRC_PASS,
                              settings.IRC_USER,
                              settings.IRC_NAME,
                              ssl=use_ssl,
                              ipv6=use_ipv6)

# load features
try:
    cfgmodlist = config.get('dr.botzo', 'module_list')

    mods = cfgmodlist.split(',')
    for mod in mods:
        irc.load_module(mod)
except NoOptionError as e:
    log.warning("You seem to be missing a module_list config option, which "
                "you probably wanted.")

# loop forever
irc.process_forever()

# vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;