#!/bin/sh

# Bugs to aplanas@suse.de

# This helper script is used to populate the SUSE theme, that is based
# on the default OpenStack theme.  SUSE theme needs the resources from
# the default theme, so using the new mechanism (from Mitaka) based on
# the AVAILABLE_THEMES, the default one will be selectable fo the
# user.  This script will collect the data from both themes, but make
# the SUSE one the only option for the dashboard.

PREFIX=/srv/www/openstack-dashboard
LOCAL=$PREFIX/openstack_dashboard/local
THEME_CONF=$LOCAL/local_settings.d/_10_use_suse_theme.py

DEFAULT_THEME="('default', 'Default', 'themes/default'),"

# By default there is not compression
compress=0

function usage
{
    echo "usage: openstack-dashboard-theme-install [[-c] | [-h]]"
}

# Read parameters
while [ "$1" != "" ]; do
    case $1 in
        -c | --compress)
	    shift
            compress=1
            ;;
        -h | --help)
            usage
            exit
            ;;
        *)
            usage
            exit 1
    esac
    shift
done

# Makes sure that the default theme is enabled
if [ -e $THEME_CONF ] ; then
    sed --in-place s_"#${DEFAULT_THEME}"_"${DEFAULT_THEME}"_g $THEME_CONF
fi

# Collect all the static assets
su wwwrun -s /bin/sh -c "python /srv/www/openstack-dashboard/manage.py collectstatic --noinput --clear > /dev/null"

# Compress the assets, this will speedup the first load
if [ "$compress" = "1" ]; then
    su wwwrun -s /bin/sh -c "python /srv/www/openstack-dashboard/manage.py compress --force > /dev/null"
fi

# Disable the default theme
if [ -e $THEME_CONF ] ; then
    sed --in-place s_"${DEFAULT_THEME}"_"#${DEFAULT_THEME}"_g $THEME_CONF
fi

# Clear the data from memcached
memcached=$(PYTHONPATH=/srv/www/openstack-dashboard \
DJANGO_SETTINGS_MODULE=openstack_dashboard.settings \
python -c "
from openstack_dashboard.settings import CACHES

# Check if the CACHES is populated
if CACHES and 'LOCATION' in CACHES['default']:
  address = CACHES['default']['LOCATION'][0]
  print address.replace(':', ' ')
") || ''
if [ -n "$memcached" ]; then
  echo 'flush_all' | nc $memcached >> /dev/null
fi
