#!/usr/local/bin/python

"""
sbin/web2ldap.py - startscript for running as stand-alone HTTP server

web2ldap -  web-based LDAP Client, see http://www.web2ldap.de
(c) by Michael Stroeder <michael@stroeder.com>

This software is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)
"""

import sys,os

exec_startdir = os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.path.insert(0,os.path.join(exec_startdir,'pylib'))
sys.path.insert(0,os.path.join(exec_startdir,'etc','web2ldap'))

if os.name == 'posix':
  # For finding web2ldapcnf.py in /etc/web2ldap on Unix systems
  sys.path.append('/etc/web2ldap')

import web2ldapcnf.misc,web2ldapcnf.standalone
for i in web2ldapcnf.misc.pylibdirs:
  sys.path.insert(0,i)

import w2lapp.core,w2lapp.handler,msHTTPServer,msHTTPHandler,ipadr

class web2ldapHTTPHandlerClass(msHTTPHandler.HTTPHandlerClass):
  script_name = '/web2ldap'
  server_env = {
    'SERVER_SOFTWARE':'webldap %s' % w2lapp.__version__,
    'SERVER_ADMIN':web2ldapcnf.standalone.server_admin,
    'DOCUMENT_ROOT':web2ldapcnf.standalone.document_root,
    'SERVER_SIGNATURE':web2ldapcnf.standalone.server_signature,
  }
  dir_listing_allowed = web2ldapcnf.standalone.dir_listing_allowed
  access_allowed   = map(ipadr.AddrMask_Str2Tuple,web2ldapcnf.standalone.access_allowed)
  extensions_map = msHTTPHandler.getExtensionMap(web2ldapcnf.standalone.mime_types)

  # Start web2ldap itself.
  def run_app(self,http_env):
    msHTTPHandler.HTTPHandlerClass.run_app(self,http_env)
    # Call web2ldap application handler function
    w2lapp.handler.HandleHTTPRequest(self.rfile,self.wfile,self.error_log,http_env)
    return

server_address,run_detached,run_threaded,ssl_enabled,uid = \
  msHTTPServer.GetCommandlineParams(
    ['127.0.0.1',1760],
    os.name == 'posix',
    1,
    web2ldapcnf.standalone.ssl_Engine=='on',
    web2ldapcnf.standalone.run_username
  )

# Open log files if running detached
if run_detached:
  web2ldapHTTPHandlerClass.access_log = open(web2ldapcnf.standalone.access_log,'a',1)
  web2ldapHTTPHandlerClass.error_log = open(web2ldapcnf.standalone.error_log,'a',1)
  web2ldapHTTPHandlerClass.debug_log = open(web2ldapcnf.standalone.debug_log,'a',1)
else:
  web2ldapHTTPHandlerClass.access_log = sys.stdout
  web2ldapHTTPHandlerClass.error_log = sys.stderr
  web2ldapHTTPHandlerClass.debug_log = sys.stdout

if run_detached:
  if os.fork():
    sys.exit(0)
  else:
    os.setsid()
    sys.stderr.close()
    sys.stderr = web2ldapHTTPHandlerClass.error_log
#    sys.stdout.close()
#    sys.stdout = web2ldapHTTPHandlerClass.debug_log

if run_detached:
  # Write PID to file
  open(web2ldapcnf.standalone.pid_file,'w').write(str(os.getpid()))

# Create instance of Thread object for cleaning-up expired sessions
cleanUpThread = w2lapp.core.CleanUpThread(
  w2lapp.core.session,interval=5
)
# Start the clean-up thread
cleanUpThread.start()

try:
  msHTTPServer.RunServer(
    web2ldapHTTPHandlerClass,
    server_address,
    run_detached,
    run_threaded, # run threaded in any case
    ssl_enabled,
    uid,
    web2ldapcnf.standalone.ssl_randfile,
    web2ldapcnf.standalone.ssl_Protocols,
    web2ldapcnf.standalone.ssl_CertificateFile,
    web2ldapcnf.standalone.ssl_CertificateKeyFile,
    web2ldapcnf.standalone.ssl_CACertificateFile,
    web2ldapcnf.standalone.ssl_VerifyClient,
    web2ldapcnf.standalone.ssl_VerifyDepth,
  )
finally:
  # Stop clean-up thread
  cleanUpThread.enabled=0
  try:
    os.remove(web2ldapcnf.standalone.pid_file)
  except IOError:
    pass
