#!/usr/bin/env python

# USAGE: python compclustweb-scgi.py -p <PORT#> -l <LOGFILE>
import shelve
import sys
import copy

stderr = copy.copy(sys.stderr)

from scgi.quixote_handler import QuixoteHandler, main
from scgi import scgi_server
from quixote.session import SessionManager
from quixote import enable_ptl

from compClust.gui.CompClustWebSession import CompClustWebSession, \
                                              CompClustWebSessionManager, \
                                              CompClustWebPublisher, \
                                              datamanager
ROOT_NAMESPACE="compClust.gui.CompClustWeb"
                                         
class CompClustSCGIHandler(QuixoteHandler):
  publisher_class = CompClustWebPublisher
  root_namespace = ROOT_NAMESPACE

def usage():
  print >>sys.stderr, "usage: python compclustweb-scgi base_url [port]"
  print >>sys.stderr, ""
  print >>sys.stderr, "base_url is the url in your apache namespace that points to the application"
  print >>sys.stderr, ""
  print >>sys.stderr, "port is which port to listen on for connections,"
  print >>sys.stderr, "  currently defaults to 8001"

class Usage(Exception):
  def __init__(self, msg=None):
    self.msg = msg
    
def main(argv=None):
  """Man function, designed to make launching from within an interpreter 
  easier. Taken from Guido's blog
  http://www.artima.com/weblogs/viewpost.jsp?thread=4829
  """
  try:
    if argv is None:
      argv = sys.argv
    print argv
    if len(argv) < 2 or len(argv) > 3:
      raise UsageError()
    #enable_ptl()
    from compClust.gui import CompClustWeb 
    CompClustSCGIHandler.prefix = argv[1]
  
    CompClustWeb.ROOT_URL = argv[1]
    if len(argv) > 2:
      PORT = int(argv[2])
    else:
      PORT = 3000
    scgi_server.SCGIServer(CompClustSCGIHandler, port=PORT).serve()
  except Usage, err:
    usage()
    return 1
  else:
    return 0


if __name__ == '__main__':
  sys.exit(main(sys.argv))
