# Path: txircd/ircd.py
# class IRCProtocol(irc.IRC):
# class IRCD(Factory):
#     def __init__(self, ip):
#     def connectionMade(self):
#     def dataReceived(self, data):
#     def checkData(self):
#     def ping(self, intervals):
#     def handleCommand(self, command, prefix, params):
#     def sendLine(self, line):
#     def connectionLost(self, reason):
#     def __init__(self, config, options = None, sslCert = None):
#     def all_module_load(self):
#     def rehash(self):
#     def load_options(self, options):
#     def cleanup(self):
#     def connect_server(self, servername):
#         def sendServerHandshake(protocol, password):
#     def server_autoconnect(self):
#     def load_module(self, name):
#     def unload_module_data(self, name):
#     def save_module_data(self):
#     def save_serialized(self, _ = None):
#     def saveClientPort(self, desc, port):
#     def saveServerPort(self, desc, port):
#     def rebind_ports(self):
#         def addClientPortToIRCd(port, ircd, desc):
#         def addServerPortToIRCd(port, ircd, desc):
#         def logPortNotBound(error):
#     def buildProtocol(self, addr):
#     def unregisterProtocol(self, p):
# 
# Path: txircd/server.py
# class ServerFactory(Factory):
#     protocol = ServerProtocol
#     
#     def __init__(self, ircd):
#         self.ircd = ircd
#         self.ircd.server_factory = self
#     
#     def buildProtocol(self, addr):
#         proto = self.protocol(self.ircd)
#         proto.factory = self
#         proto.localOrigin = False
#         return proto
# 
# Path: txircd/utils.py
# def resolveEndpointDescription(desc):
#     result = []
#     current = []
#     depth = 0
#     desc = iter(desc)
#     for letter in desc:
#         if letter == "\\":
#             try:
#                 nextchar = desc.next()
#             except StopIteration:
#                 raise ValueError ("Malformed endpoint description; escaped end of string")
#             if nextchar in "{}":
#                 current.append(nextchar)
#             else:
#                 current.extend((letter, nextchar))
#         elif letter == "{":
#             if depth == 0:
#                 result.append("".join(current))
#                 current = []
#             else:
#                 current.append(letter)
#             depth += 1
#         elif letter == "}":
#             depth -= 1
#             if depth == 0:
#                 result.append(escapeEndpoint(resolveEndpointDescription("".join(current))))
#                 current = []
#             else:
#                 current.append(letter)
#         else:
#             current.append(letter)
#     if depth != 0:
#         raise ValueError ("Malformed endpoint description; braces do not match")
#     result.append("".join(current))
#     return "".join(result)


from twisted.internet import reactor, ssl
from twisted.internet.endpoints import serverFromString
from twisted.python import log
from txircd.ircd import IRCD, default_options
from txircd.server import ServerFactory
from txircd.utils import resolveEndpointDescription
from OpenSSL import SSL
import yaml, collections, sys, signal
    import argparse
    options = default_options.copy()
    # Parse command line
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="txircd.yaml")
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true")
    parser.add_argument("-l", "--log-file", dest="log_file", type=argparse.FileType('a'), default=sys.stdout)
    args = parser.parse_args()
    # Load config file
    try:
        with open(args.config) as f:
            options.update(yaml.safe_load(f))
    except:
        print "Error: Loading configuration file" # Oh well
    if options["app_verbose"] or args.verbose:
        log.startLogging(args.log_file)
    ssl_cert = ChainedOpenSSLContextFactory(options["app_ssl_key"],options["app_ssl_pem"])
    ssl_cert.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True) # We can ignore the validity of certs to get what we need
    ircd = IRCD(args.config, options, ssl_cert)
    serverlink_factory = ServerFactory(ircd)
    for portstring in options["server_client_ports"]:
        try:
            endpoint = serverFromString(reactor, resolveEndpointDescription(portstring))
        except ValueError as e:
            log.msg("Could not bind {}: not a valid description ({})".format(portstring, e))
            continue
        listenDeferred = endpoint.listen(ircd)
        listenDeferred.addCallback(addClientPortToIRCd, ircd, portstring)
        listenDeferred.addErrback(logPortNotBound)
    for portstring in options["server_link_ports"]:
        try:

# Path: txircd/ircd.py
# class IRCProtocol(irc.IRC):
# class IRCD(Factory):
#     def __init__(self, ip):
#     def connectionMade(self):
#     def dataReceived(self, data):
#     def checkData(self):
#     def ping(self, intervals):
#     def handleCommand(self, command, prefix, params):
#     def sendLine(self, line):
#     def connectionLost(self, reason):
#     def __init__(self, config, options = None, sslCert = None):
#     def all_module_load(self):
#     def rehash(self):
#     def load_options(self, options):
#     def cleanup(self):
#     def connect_server(self, servername):
#         def sendServerHandshake(protocol, password):
#     def server_autoconnect(self):
#     def load_module(self, name):
#     def unload_module_data(self, name):
#     def save_module_data(self):
#     def save_serialized(self, _ = None):
#     def saveClientPort(self, desc, port):
#     def saveServerPort(self, desc, port):
#     def rebind_ports(self):
#         def addClientPortToIRCd(port, ircd, desc):
#         def addServerPortToIRCd(port, ircd, desc):
#         def logPortNotBound(error):
#     def buildProtocol(self, addr):
#     def unregisterProtocol(self, p):
# 
# Path: txircd/server.py
# class ServerFactory(Factory):
#     protocol = ServerProtocol
#     
#     def __init__(self, ircd):
#         self.ircd = ircd
#         self.ircd.server_factory = self
#     
#     def buildProtocol(self, addr):
#         proto = self.protocol(self.ircd)
#         proto.factory = self
#         proto.localOrigin = False
#         return proto
# 
# Path: txircd/utils.py
# def resolveEndpointDescription(desc):
#     result = []
#     current = []
#     depth = 0
#     desc = iter(desc)
#     for letter in desc:
#         if letter == "\\":
#             try:
#                 nextchar = desc.next()
#             except StopIteration:
#                 raise ValueError ("Malformed endpoint description; escaped end of string")
#             if nextchar in "{}":
#                 current.append(nextchar)
#             else:
#                 current.extend((letter, nextchar))
#         elif letter == "{":
#             if depth == 0:
#                 result.append("".join(current))
#                 current = []
#             else:
#                 current.append(letter)
#             depth += 1
#         elif letter == "}":
#             depth -= 1
#             if depth == 0:
#                 result.append(escapeEndpoint(resolveEndpointDescription("".join(current))))
#                 current = []
#             else:
#                 current.append(letter)
#         else:
#             current.append(letter)
#     if depth != 0:
#         raise ValueError ("Malformed endpoint description; braces do not match")
#     result.append("".join(current))
#     return "".join(result)


# Path: app.py
from twisted.internet import reactor, ssl
from twisted.internet.endpoints import serverFromString
from twisted.python import log
from txircd.ircd import IRCD, default_options
from txircd.server import ServerFactory
from txircd.utils import resolveEndpointDescription
from OpenSSL import SSL
import yaml, collections, sys, signal
    import argparse

    options = default_options.copy()
    # Parse command line
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="txircd.yaml")
    parser.add_argument("-v", "--verbose", dest="verbose", action="store_true")
    parser.add_argument("-l", "--log-file", dest="log_file", type=argparse.FileType('a'), default=sys.stdout)
    args = parser.parse_args()
    # Load config file
    try:
        with open(args.config) as f:
            options.update(yaml.safe_load(f))
    except:
        print "Error: Loading configuration file" # Oh well
    if options["app_verbose"] or args.verbose:
        log.startLogging(args.log_file)
    ssl_cert = ChainedOpenSSLContextFactory(options["app_ssl_key"],options["app_ssl_pem"])
    ssl_cert.getContext().set_verify(SSL.VERIFY_PEER, lambda connection, x509, errnum, errdepth, ok: True) # We can ignore the validity of certs to get what we need
    ircd = IRCD(args.config, options, ssl_cert)
    serverlink_factory = ServerFactory(ircd)
    for portstring in options["server_client_ports"]:
        try:
            endpoint = serverFromString(reactor, resolveEndpointDescription(portstring))
        except ValueError as e:
            log.msg("Could not bind {}: not a valid description ({})".format(portstring, e))
            continue
        listenDeferred = endpoint.listen(ircd)
        listenDeferred.addCallback(addClientPortToIRCd, ircd, portstring)
        listenDeferred.addErrback(logPortNotBound)
    for portstring in options["server_link_ports"]:
        try:

            endpoint = serverFromString(reactor, resolveEndpointDescription(portstring))