#!/usr/bin/env python
#
#  Copyright 2010, 2011 G24
#
#    This file is part of guppy.
#
#    guppy 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.
#
#    guppy 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 guppy.  If not, see <http://www.gnu.org/licenses/>.
import argparse
import sys
import os
import ConfigParser
import irc
import threading, time

class main(object):
    def __init__(self):
        # Constant.
        self.version = "0.4.0"
        print("  __ _ _   _ _ __  _ __  _   _ ")
        print(" / _` | | | | '_ \| '_ \| | | | http://repo.or.cz/w/guppy.git/summary")
        print("| (_| | |_| | |_) | |_) | |_| |")
        print(" \__, |\__,_| .__/| .__/ \__, |")
        print(" |___/      |_|   |_|    |___/  version "+self.version)
        print("")

        if 'HOME' in os.environ:
            self.directory = os.environ['HOME'] + '/.guppy/'
        elif 'HOMEPATH' in os.environ:
            self.directory = os.environ['HOMEPATH'] + '/.guppy/'
        else:
            self.directory = os.getcwd() + '/conf/'

        print("Settings directory: %s" % self.directory)

        if not os.path.exists(self.directory):
            os.makedirs(self.directory)
        self.configpath = self.directory + 'main.cfg'
        self.logpath = self.directory + 'main.log'

        parser = argparse.ArgumentParser(description="Start guppy - a modular Python IRC bot.")
        parser.add_argument("-c", "--makeconf", required=False, help="generate a new configuration file",action='store_true')
        parser.add_argument("-v", "--version", required=False, help="display version information and exit.",action='store_true')
        args = parser.parse_args(sys.argv[1:])
        if args.version == True:
            exit()

        if os.path.isfile(self.configpath) == False: 
            print("No configuration file found, running makeconf")
            self.makeconf()
        
        if args.makeconf == True:
            self.makeconf()

        self.config = ConfigParser.RawConfigParser()
        self.config.read(self.configpath)
        
    def start(self):
        for section in self.config.sections():
            server_config = {}
            server_config["host"] = section
            server_config["confdir"] = self.directory
            for item,value in self.config.items(section):
                server_config[item] = value
            
            # since IRC is a subclass of threading.Thread, using 
            # .start() on it will automatically run it in a new thread.
            conn = irc.IRC(server_config)
            conn.daemon = True
            conn.start()
        
        while threading.activeCount() > 1:
            time.sleep(15)
    
    def stop(self):
        for client in threading.enumerate():
            if client.__class__.__name__ != "_MainThread":
                client.doQuit("Keyboard interrupt.")
            
    def my_raw(self,prompt="", default=""):
        ret = raw_input("%s [%s]: "%(prompt,default))
        return default if ret == "" else ret
        
    def set(self,section,option,text,default=""):
        try:
            if default == "":
                default = self.config.get(section,option)
        except ConfigParser.NoOptionError:
            pass
        
        value = self.my_raw(text,default)
        self.config.set(section,option,value)
        
    def makeconf(self):
        self.config = ConfigParser.RawConfigParser()
        getting_servers = True
        while getting_servers:
            currentServer = self.my_raw("IRC server to connect to")
            try:
                self.config.add_section(currentServer)
            except ConfigParser.DuplicateSectionError:
                overwrite = self.my_raw("Server already exists! Overwrite? (yes/no)", "no").lower()
                while overwrite != "yes" and overwrite != "y" and overwrite != "no" and overwrite != "n":
                    overwrite = self.my_raw("Invalid option. Overwrite configuration for "+currentServer+"? (yes/no)", "no").lower()
                    
                if overwrite.lower() == "no" or overwrite.lower() == "n":
                    continue #go back to top of "while getting_servers:"
                #else continue out of try/except
            
            self.set(currentServer,'channels',"Channels to automatically join (comma-separated, no spaces)")
            self.set(currentServer,'nickname',"My nickname")
            self.set(currentServer,'ident',"My ident")
            self.set(currentServer,'ns_name',"NickServ username (if there is none, press ENTER)")
            self.set(currentServer,'ns_pwd',"NickServ password (if there is none, press ENTER)")
            self.set(currentServer,'port',"Port", "6667")
            self.set(currentServer,"comchar","My command char", "-")
            self.set(currentServer,"plugins","Plugins to load on startup (comma-separated, no spaces)", "auth,printer,pluginloader")
            
            another_server = self.my_raw("All done with "+currentServer+". Add another server? (yes/no)", "no").lower()
            while another_server != "yes" and another_server != "y" and another_server != "no" and another_server != "n":
                another_server = self.my_raw("Invalid option. Do you want to add another server? (yes/no)", "no").lower()
            
            if another_server == "no" or another_server == "n":
                break
            #else no action needed
        
        self.writeconfig()
        print('Configuration file has been created.')
        exit()
        
    def writeconfig(self):
        configfile = open(self.configpath, 'w')
        self.config.write(configfile)
        configfile.close()

if __name__ == "__main__":
    c = None
    try:
        c = main()
        c.start()
        print("All connections were closed, exiting.")
    except KeyboardInterrupt:
        print("Shutting down all connections...")
        c.stop()
        print("Quitting!")
        time.sleep(2) # to let connections close