#!/bin/bash
set -eux

install-packages libapache2-mod-wsgi libssl-dev libffi-dev gettext

TEMPLATE_ROOT="$(os-apply-config --print-templates)"
FILES="$(dirname $0)/../files/"
HORIZON_CONF=/etc/httpd/conf.d/horizon.conf
PORTS_CONF=/etc/httpd/conf.d/ports.conf

if [ -d /etc/httpd ]; then
    # This is required to allow different ports configuration
    # e.g haproxy or apache listening on 80
    sed -i '/Listen/s/^/#/g' /etc/httpd/conf/httpd.conf
    mkdir -p "${TEMPLATE_ROOT}/etc/httpd/conf.d/"
    for FILE in "${HORIZON_CONF}" "${PORTS_CONF}"; do
        install -m 0644 -o root -g root "${FILES}${FILE}" "${TEMPLATE_ROOT}${FILE}"
    done
    sed -e "s|HORIZON_VENV_DIR|${HORIZON_VENV_DIR}|g" -i "${TEMPLATE_ROOT}/etc/httpd/conf.d/horizon.conf"
fi

if [ -d /etc/apache2 ]; then
    mkdir -p "${TEMPLATE_ROOT}/etc/apache2/sites-available"
    install -m 0644 -o root -g root "${FILES}${HORIZON_CONF}" "${TEMPLATE_ROOT}/etc/apache2/sites-available/"
    install -m 0644 -o root -g root "${FILES}${PORTS_CONF}" "${TEMPLATE_ROOT}/etc/apache2/ports.conf"
    ln -s /etc/apache2/sites-available/horizon.conf /etc/apache2/sites-enabled/horizon.conf
    [ ! -d /var/log/httpd ] && ln -s /var/log/apache2 /var/log/httpd
    rm -f /etc/apache2/sites-enabled/{000-default.conf,default.conf,default-ssl.conf}
    sed -e "s|HORIZON_VENV_DIR|${HORIZON_VENV_DIR}|g" -i "${TEMPLATE_ROOT}/etc/apache2/sites-available/horizon.conf"
fi

os-svc-install ${HORIZON_EXTRA_INSTALL_OPTS} -i "${HORIZON_VENV_DIR}" -u horizon -r /opt/stack/horizon
set +u
source "${HORIZON_VENV_DIR}/bin/activate"
set -u
pip install python-memcached
write-pip-manifest horizon
set +u
deactivate
set -u

if [ ! -d /var/www/horizon/static ]; then
    mkdir -p /var/www/horizon/static
    chown -R horizon:horizon /var/www/horizon
fi

# Django won't start otherwise:
touch /etc/horizon/.secret_key_store
chmod 600 /etc/horizon/.secret_key_store
chown horizon:horizon /etc/horizon/.secret_key_store

# Workaround for https://bugs.launchpad.net/osprofiler/+bug/1361235
sed -i "s#'../..'#os.path.realpath('../..')#" "$HORIZON_VENV_DIR"/lib/python2.7/site-packages/openstack_dashboard/wsgi/django.wsgi

# We need to splice this into local_settings.py at configuration time
ENVDIR="$(os-refresh-config --print-base)/environment.d"
mkdir -p "${ENVDIR}"
echo "export HORIZON_VENV_DIR='${HORIZON_VENV_DIR}'" > "${ENVDIR}/10-horizon-venv-dir.bash"
