#
# main.py
#	Main driver for WWW-Usenet interface
#
import sys, time, os
import chore
import utils
from get import GET_mixin
from put import PUT_mixin
from chore.authen import Authen_mixin, Authen_Server_mixin

# Tie our various handlers together
class App_Handler(chore.handlers.Chore_Handler, GET_mixin,
        PUT_mixin, Authen_mixin):
    def __init__(self, conn, tup, approot):
	chore.handlers.Chore_Handler.__init__(self, conn, tup, approot,
	    (GET_mixin.__init__,
	     PUT_mixin.__init__,
             Authen_mixin.__init__))

# Load our configuration file
#
# This includes configuring our config file elements,
#  then processing the supplied file.
def load_cfg(fn):

    # A configurator
    c = chore.config.Config()

    # Let the web network side add its config entries
    chore.www.add_config(c)

    # Here's how our config file looks
    c.onearg.add( ("files",) )
    c.mults.add( ("files",) )
    c.onearg.add( ("files", "path") )

    # Parse the input
    cfg = c.load_cfg(fn)

    # Preload any file indices
    for tup in cfg["files"]:
        d = tup[1]["path"]
        fn = d + ".idx"
        if os.access(fn, os.R_OK):
            tup[1]["_index"] = utils.load_index(fn)
    return cfg

# Root of our app server
class App(chore.server.Server, Authen_Server_mixin):

    def __init__(self, config):
	# Let Chore handle most things
	chore.server.Server.__init__(self, config, App_Handler);

        # Authen server
        Authen_Server_mixin.__init__(self)
        self.authentication.append(Authen_mixin.auth_server)
        self.init_acct_server()

if __name__ == "__main__":
    if len(sys.argv) != 2:
	sys.stderr.write("Usage is: %s <config-file>\n" %
	    (sys.argv[0],))
	sys.exit(1)

    # Create the server with config
    app = App(load_cfg(sys.argv[1]))

    # It's an HTTP service
    app.start_http()

    # HTTP servers each get their own thread.
    # We could run a CLI here and like, dunno,
    #  do stuff?
    while True:
	time.sleep(60)
