# Django settings for sp project.

import os
import pfconfigxml
from django.conf import global_settings

PROJECT_PATH = os.path.dirname(os.path.dirname(__file__))

DEBUG = os.environ.get('DEBUG') == 'yes'
TEMPLATE_DEBUG = DEBUG

# fastcgi (see http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/)
FORCE_SCRIPT_NAME=''

ADMINS = ()
MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': '/var/db/univnautes-sp.sqlite3',
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Paris'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-fr'

SITE_ID = 1

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

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.join(PROJECT_PATH, 'www', 'static')

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY_FILENAME = os.path.join(PROJECT_PATH, 'secret.key')
try:
    with open(SECRET_KEY_FILENAME, 'rb') as sk:
        SECRET_KEY = sk.read()
except IOError:
    import random, string
    SECRET_KEY = "".join([random.SystemRandom().choice(string.digits + string.letters + string.punctuation) for i in range(100)])
    with open(SECRET_KEY_FILENAME, 'wb') as sk:
        sk.write(SECRET_KEY)

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

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'sp.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'sp.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_PATH, 'sp', 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'authentic2.idp',
    'authentic2.attribute_aggregator',
    'authentic2.saml',
    'authentic2.authsaml2',
    'sp',
)

if DEBUG:
    INSTALLED_APPS += ('django.contrib.admin',)

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
# it can't be 'django.contrib.sessions.serializers.JSONSerializer' with authentic2 (attributes)

SESSION_COOKIE_NAME = 'univnautes-sp-sessionid'
SESSION_ENGINE = 'django.contrib.sessions.backends.file'
SESSION_FILE_PATH = '/var/tmp/univnautes-sp-sessions'
try:
    os.mkdir(SESSION_FILE_PATH)
except:
    pass

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

LOGIN_REDIRECT_URL = '/'


# logging configuration
# FIXME : syslog (freebsd -> /var/run/log) / local4 / debug
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
    'tmpspfile': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/tmp/sp.log'
    },
    },
    'loggers': {
        'django.request': {
            'handlers': ['tmpspfile'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

# authentic2 settings (SP)
LOCAL_METADATA_CACHE_TIMEOUT = 600
SAML_METADATA_ROOT = 'metadata'
SAML_METADATA_AUTOLOAD = 'none'

AUTH_FRONTENDS = ('authentic2.authsaml2.frontend.AuthSAML2Frontend',)
AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'authentic2.authsaml2.backends.AuthSAML2PersistentBackend',
        'authentic2.authsaml2.backends.AuthSAML2TransientBackend')

# pfSense captive portal commands :
UNIVNAUTES_CP_ALLOW_CMD = [
        os.path.join(PROJECT_PATH, 'cp_allow'),
        'cpzone=%(cpzone)s',
        'ip=%(ip)s',
        'username=%(username)s',
        'nameid=%(nameid)s',
        'multiple=%(multiple)s']

UNIVNAUTES_CP_DISCONNECT_CMD = [
        os.path.join(PROJECT_PATH, 'cp_disconnect'),
        'cpzone=%(cpzone)s',
        'ip=%(ip)s']

UNIVNAUTES_CP_GET_SESSIONS_CMD = os.path.join(PROJECT_PATH, 'cp_get_sessions')

# now get some values from config.xml
# => server must be restarted if config.xml is changed

if 'CONFIG_XML' in os.environ:
    # for run this application outside a real pfSense
    CONFIG_XML = os.environ['CONFIG_XML']
else:
    CONFIG_XML = '/cf/conf/config.xml'

sp = pfconfigxml.get_sp()
# SAML certificate
SAML_SIGNATURE_PUBLIC_KEY = sp.get('saml_cert', {}).get('crt')
SAML_SIGNATURE_PRIVATE_KEY = sp.get('saml_cert', {}).get('prv')

# SESSION_COOKIE_AGE from pfsenseid, at least 2 minutes
SESSION_COOKIE_AGE = max(sp.get('cp', {}).get('idletimeout', 2)*60, 2*60)

# SP User Interface parameters
SP_UI = sp.get('ui', {})
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'sp.context_processors.sp',
    )

# FIXME: get this from SP_UI config (i.e. config.xml)
PROXYMAP_URL  = 'http://lactuca.entrouvert.org/proxymap/mapbox/%(z)d/%(x)d/%(y)d.png32'

