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

    DEBUG=${DEBUG:="false"}
    # 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
    if $DEV ; then
        # activate django cors plugin for dev environment to remove need for browser cors plugin
        sed -i "s/    'django.contrib.auth',/    'corsheaders', 'django.contrib.auth',/g" pvs_instance/settings.py
        sed -i "s/    'django.contrib.sessions.middleware.SessionMiddleware',/    'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware',/g" pvs_instance/settings.py
        echo 'CORS_ORIGIN_ALLOW_ALL = True' >> pvs_instance/settings.py
    fi


    sed -e "s/SECRET_KEY = '.*'/SECRET_KEY = '${DJANGO_SECRET_KEY}'/" -i pvs_instance/settings.py
    chmod g+w -R .
    chgrp users -R .

    if [[ "$DEBUG" = true ]] ; then
        echo "DEBUG ON Setting functions"
        echo "MIDDLEWARE.append('pyinstrument.middleware.ProfilerMiddleware')" >> pvs_instance/settings.py
        sed -e 's/DEBUG = False/DEBUG = True/' -i pvs_instance/settings.py
        
        var="import os
import sys
import debugpy

def initialize_debugger():
    if not os.getenv('RUN_MAIN'):

        import debugpy
        debugpy.listen(('0.0.0.0', 5678))
"
        echo "$var" >> debug.py


        sed -i "/import sys/a from debug import initialize_debugger" manage.py
        sed -i '/execute_from_command_line(sys.argv)*/i \\    initialize_debugger()' manage.py


    fi

} 1>&2
