#!/bin/bash
{
    echo "Running configure.sh"

    # Configure instance
    sed -e "s/'disable_existing_loggers': True,/'disable_existing_loggers': False,/" -i pvs_instance/settings.py
    HANDLERS="'handlers': {\n
        'null': {\n
            'level':'DEBUG',\n
            'class':'logging.NullHandler',\n
        },\n
        'console': {\n
            'level': 'DEBUG' if DEBUG else 'INFO',\n
            'class': 'logging.StreamHandler',\n
            'formatter': 'verbose' if DEBUG else 'simple',\n
            'filters': [],\n
        },\n
    },"
    LOGGERS="'loggers': {\n
        'eoxserver': {\n
            'handlers': ['console'],\n
            'level': 'DEBUG' if DEBUG else 'INFO',\n
            'propagate': False,\n
        },
    }"
    sed -e "/^    'handlers': {$/,/^    },$/c `echo ${HANDLERS}`" -i pvs_instance/settings.py
    sed -e "/^    'loggers': {$/,/^    }$/c `echo ${LOGGERS}`" -i pvs_instance/settings.py

    sed -e "s,http_service_url=http://localhost:8000/ows,http_service_url=${APACHE_ALIAS}/ows," -i pvs_instance/conf/eoxserver.conf
    sed -e "s/resampling_method=average/resampling_method=near/" -i pvs_instance/conf/eoxserver.conf
    sed -e "s/image/jp2,GDAL/JPEG2000/#image/jp2,GDAL/JPEG2000/" -i pvs_instance/conf/formats.conf
    # TODO maxsize...

    echo "EOXS_VALIDATE_IDS_NCNAME = False" >> pvs_instance/settings.py
    echo "EOXS_OPENSEARCH_RECORD_MODEL = 'eoxserver.resources.coverages.models.Product'" >> pvs_instance/settings.py

    echo "CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': '/var/tmp/django_cache',
    }
    }" >> pvs_instance/settings.py

    sed -e "/TEMPLATE_DEBUG = DEBUG/d" -i pvs_instance/settings.py

    sed -e 's/DEBUG = True/DEBUG = False/' -i pvs_instance/settings.py

    # Further configuration
    echo "ALLOWED_HOSTS = ['*']" >> pvs_instance/settings.py
    echo "USE_X_FORWARDED_HOST = True" >> pvs_instance/settings.py
    echo "SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')" >> pvs_instance/settings.py

    chmod g+w -R .
    chgrp users -R .
} 1>&2
