#!/usr/bin/env python

#   Copyright 2010-2011 Josh Kearney
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""pyhole - A modular IRC bot for Python developers."""

import multiprocessing
import os
import sys
import time


PYHOLE_PATH = os.path.normpath(os.path.join(
        os.path.abspath(sys.argv[0]), os.pardir, os.pardir))
if os.path.exists(os.path.join(PYHOLE_PATH, "pyhole", "__init__.py")):
    sys.path.insert(0, PYHOLE_PATH)


from pyhole import irc
from pyhole import log
from pyhole import utils
from pyhole import version


__VERSION__ = version.version_string()

LOG = log.get_logger()
CONFIG = utils.get_config()


class IRCConnection(multiprocessing.Process):
    """IRC network connection process"""
    def __init__(self, irc_network):
        super(IRCConnection, self).__init__()
        self.irc_network = irc_network

    def run(self):
        """IRC network connection"""
        reconnect_delay = CONFIG.get("reconnect_delay", type="int")

        while True:
            try:
                connection = irc.IRC(self.irc_network)
            except Exception, exc:
                LOG.error(exc)
                LOG.error("Retrying in %d seconds" % reconnect_delay)
                time.sleep(reconnect_delay)
                continue

            try:
                connection.start()
            except KeyboardInterrupt:
                sys.exit(0)
            except Exception, exc:
                LOG.error(exc)
                LOG.error("Retrying in %d seconds" % reconnect_delay)
                time.sleep(reconnect_delay)
                continue


def network_list(sections):
    """Prepare the list of IRC networks"""
    return [net for net in sections if net not in ["Pyhole", "Redmine"]]


def main():
    """Main loop"""
    networks = network_list(CONFIG.sections())

    LOG.info("Starting %s" % __VERSION__)
    LOG.info("Connecting to IRC Networks: %s" % ", ".join(networks))
    for network in networks:
        proc = IRCConnection(network)
        proc.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        LOG.info("Caught KeyboardInterrupt, shutting down")


if __name__ == "__main__":
    main()
