# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Main program for Rietveld.

This is also a template for running a Django app under Google App
Engine, especially when using a newer version of Django than provided
in the App Engine standard library.

The site-specific code is all in other files: urls.py, models.py,
views.py, settings.py.
"""

# Standard Python imports.
import os
import sys
import logging

# Log a message each time this module get loaded.
logging.info('Loading %s, app version = %s',
             __name__, os.getenv('CURRENT_VERSION_ID'))

import appengine_config

# AppEngine imports.
from google.appengine.ext.webapp import util


# Helper to enter the debugger.  This passes in __stdin__ and
# __stdout__, because stdin and stdout are connected to the request
# and response streams.  You must import this from __main__ to use it.
# (I tried to make it universally available via __builtin__, but that
# doesn't seem to work for some reason.)
def BREAKPOINT():
  import pdb
  p = pdb.Pdb(None, sys.__stdin__, sys.__stdout__)
  p.set_trace()


# Custom Django configuration.
# NOTE: For obscure reasons, this must be repeated here as well as in
# appengine_config.py.  Without the duplication, we get tracebacks
# from Django complaining about ROOT_URLCONF when the first hit to a
# fresh process is /_ah/stats, and the second is /.
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
settings._target = None

# Import various parts of Django.
import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher
import django.forms

# Work-around to avoid warning about django.newforms in djangoforms.
django.newforms = django.forms


def log_exception(*args, **kwds):
  """Django signal handler to log an exception."""
  cls, err = sys.exc_info()[:2]
  logging.exception('Exception in request: %s: %s', cls.__name__, err)


# Log all exceptions detected by Django.
django.core.signals.got_request_exception.connect(log_exception)

# Unregister Django's default rollback event handler.
django.core.signals.got_request_exception.disconnect(
    django.db._rollback_on_exception)


def real_main():
  """Main program."""
  # Don't ask. :-(
  if os.getenv('HTTP_HOST') == 'codereview.appspot.com':
    if os.getenv('AUTH_DOMAIN') != 'gmail.com':
      logging.warn('Fixing auth domain (%r)', os.getenv('AUTH_DOMAIN'))
      os.environ['AUTH_DOMAIN'] = 'gmail.com'
  # Create a Django application for WSGI.
  application = django.core.handlers.wsgi.WSGIHandler()
  # Run the WSGI CGI handler with that application.
  util.run_wsgi_app(application)


def profile_main():
  """Main program for profiling."""
  import cProfile
  import pstats
  import StringIO

  prof = cProfile.Profile()
  prof = prof.runctx('real_main()', globals(), locals())
  stream = StringIO.StringIO()
  stats = pstats.Stats(prof, stream=stream)
  # stats.strip_dirs()  # Don't; too many modules are named __init__.py.
  stats.sort_stats('time')  # 'time', 'cumulative' or 'calls'
  stats.print_stats()  # Optional arg: how many to print
  # The rest is optional.
  # stats.print_callees()
  # stats.print_callers()
  print '\n<hr>'
  print '<h1>Profile</h1>'
  print '<pre>'
  print stream.getvalue()[:1000000]
  print '</pre>'

# Set this to profile_main to enable profiling.
main = real_main


if __name__ == '__main__':
  main()

@@ -2741,250 +2741,8 @@
 %22%22%22%0A
-  # Don't ask. :-(%0A  if os.getenv('HTTP_HOST') == 'codereview.appspot.com':%0A    if os.getenv('AUTH_DOMAIN') != 'gmail.com':%0A      logging.warn('Fixing auth domain (%25r)', os.getenv('AUTH_DOMAIN'))%0A      os.environ%5B'AUTH_DOMAIN'%5D = 'gmail.com'%0A
   # 

Remove a temporary hack introduced in r471 to work around a bug in the then-new authentication mechanism for Google Apps users.