# -*- coding: utf-8 -*-

"""
A Django site harness configuration by Andy Mikhailenko <andy at neithere dot net>.
Based on the Byteflow conf: http://hg.piranha.org.ua/byteflow/
The most recent version can be found at http://bitbucket.org/neithere/django-harness/
"""

#
# DO NOT EDIT THIS FILE!
#
# Please edit conf/settings.py to override attributes defined here or add your own ones.
#

import logging
import os.path
import random
import sys

log = logging.getLogger('harness')


# Set project root relative to manage.py
PROJECT_ROOT = sys.path[0]

# This function is only used within this file
at_project_root = lambda name: os.path.join(PROJECT_ROOT, name)

# Define paths where to look for your Django apps (see documentation for details).
# Note that the entries are inserted in reversed order.
# The project root should remain in the first position.
for app_lookup_path in ('compat', 'apps'):
    sys.path.insert(1, at_project_root(app_lookup_path))

DEBUG = True

# Local time zone for this installation. All choices can be found here:
# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
TIME_ZONE = 'UTC'

# Language code for this installation. All choices can be found here:
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
# http://blogs.law.harvard.edu/tech/stories/storyReader$15
LANGUAGE_CODE = 'en'

SITE_ID = 1

# These constants appear in default templates and are useful for basic SEO
SITE_NAME = SITE_KEYWORDS = SITE_DESCRIPTION = ''

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT  = at_project_root('media')
STATIC_ROOT = at_project_root('static')

# URL that handles the media served from MEDIA_ROOT.
# Example: "http://media.lawrence.com"
MEDIA_URL  = '/media/'
STATIC_URL = '/static/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/admin-media/'

# Don't share it with anybody
if not hasattr(globals(), 'SECRET_KEY'):
    secret_file = at_project_root('local_secret.txt')
    try:
        SECRET_KEY = open(secret_file).read().strip()
    except IOError:
        try:
            chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
            SECRET_KEY = ''.join([random.choice(chars) for i in range(50)])
            secret = file(secret_file, 'w')
            secret.write(SECRET_KEY)
            secret.close()
        except IOError:
            raise Exception('Please create file %s filled with random characters'
                            ' to serve as your secret key.' % secret_file)
    del secret_file

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.csrf.middleware.CsrfMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'harness.middleware.ThreadIPMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'harness.middleware.ThreadUserMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = [
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
]

try:
    import django.contrib.messages
except ImportError:
    # Django < 1.2
    pass
else:
    MIDDLEWARE_CLASSES += (
        'django.contrib.messages.middleware.MessageMiddleware',
    )
    TEMPLATE_CONTEXT_PROCESSORS += [
        'django.contrib.messages.context_processors.messages'
    ]

# Try using custom template context processors.
#
#   Example context_processors module:
#   >>> processors = ('my_vars',)
#   >>> def my_vars(request):
#   >>>     return {'foo': 'bar'}
try:
    from context_processors import processors
except ImportError:
    pass
else:
    import warnings
    warnings.warn('Implicit context_processors import is deprecated. Use '
                  'ADDITIONAL_CONTEXT_PROCESSORS variable instead.',
                  DeprecationWarning)
    del warnings
    for fname in processors:
        TEMPLATE_CONTEXT_PROCESSORS.append('context_processors.%s' % fname)
    del processors

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    at_project_root('templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.sitemaps',
    'django.contrib.flatpages',
    'django.contrib.markup',
)

# Override some constants with site-specific ones
try:
    from settings import *
except ImportError:
    import sys
    sys.stderr.write('Unable to read settings.py\n')
    sys.exit(1)

# Override even site-specific constants with installation-related ones
# (e.g. locally use a test SQLite database instead of MySQL on production server)
try:
    from settings_local import *
except ImportError: pass

# Warn if project is marked as designed for a version of Django different from current.
# This can give a hint if something gets broken.
try:
    ver = REQUIRE_DJANGO_VERSION
except:
    pass
else:
    if isinstance(ver, (basestring, float)):
        ver = tuple(int(x) for x in str(ver).split('.'))
    assert isinstance(ver, tuple), ('DJANGO_VERSION must be string, float or '
                                    'tuple, e.g. "1.0", 1.0 or (1,0).')
    assert 1 < len(ver) < 3, 'DJANGO_VERSION tuple must contain between 1 and 3 integers'
    for i in range(0, len(ver)):
        assert isinstance(ver[i], int), 'Integer expected at DJANGO_VERSION[%d] but got %s' % (i, type(ver[i]))
    from django import VERSION, get_version
    if not ver == VERSION[:len(ver)]:
        str_ver = '.'.join(str(i) for i in ver)
        msg = 'This project was designed for Django %s. You have Django %s installed.\n'\
              'Please ensure there are no problems and update REQUIRE_DJANGO_VERSION '\
              'variable in project settings.' % (str_ver, get_version())
        from warnings import warn
        warn(msg, UserWarning)
    # cleanup
    del(VERSION)
    del(get_version)

try:
    MANAGERS = ADMINS
except NameError:
    raise NameError, "ADMINS variable must be specified in this form: (('Your Name', 'your_email@domain.com'),)"

try:
    TEMPLATE_DEBUG
except NameError:
    TEMPLATE_DEBUG = DEBUG

try:
    INSTALLED_APPS += ADDITIONAL_APPS
except NameError: pass

try:
    MIDDLEWARE_CLASSES += ADDITIONAL_MIDDLEWARE
except NameError: pass

try:
    TEMPLATE_CONTEXT_PROCESSORS += ADDITIONAL_TEMPLATE_CONTEXT_PROCESSORS
except NameError: pass

# Fix relative paths to SQLite databases under most production environments
def fix_sqlite_path(engine, name):
    if 'sqlite' in engine and not name.startswith('/'):
        return at_project_root(name)
    else:
        return name
try:
    DATABASE_NAME = fix_sqlite_path(DATABASE_ENGINE, DATABASE_NAME)
except NameError:
    DATABASES['default']['NAME'] = fix_sqlite_path(DATABASES['default']['ENGINE'],
                                                   DATABASES['default']['NAME'])

# Virtual environment support. If VIRTUALENV is defined and not empty, we will
# use its site-packages.
try:
    VIRTUALENV
except NameError:
    VIRTUALENV = None
else:
    if VIRTUALENV:
        log.debug('(harness) Using virtual environment %s'%VIRTUALENV)
        if '/site-packages/' not in VIRTUALENV:
            # assert partial path is defined, i.e. the VE root path, not that
            # of the site-packages directory, so add the necessary info
            _ver = 'python%d.%d' % (sys.version_info[0], sys.version_info[1])
            _new_path = os.path.join(VIRTUALENV, 'lib', _ver, 'site-packages')
            log.debug('(harness) Adding site packages from %s'%_new_path)
            VIRTUALENV = _new_path
            del _new_path, _ver
        import site
        site.addsitedir(VIRTUALENV)


del log
