#!/bin/sh

set -e
#set -x

. /usr/share/debconf/confmodule
. /usr/share/dbconfig-common/dpkg/postinst.mysql 
dbc_sql_substitutions=1
dbc_generate_include=template:/etc/tweet-django/dbsettings.py
dbc_generate_include_args=-otemplate_infile=/usr/share/tweet-django/debian/dbsettings.py.template
dbc_generate_include_owner=root:www-data
dbc_generate_include_perms=0640
dbc_go tweet-django $@

if [ "$1" = configure ] ; then
    random_key=$( env LANG=C LC_ALL=C tr -dc "[:alnum:]" < /dev/urandom | dd bs=1 count=63 2> /dev/null )
    tempfile=`tempfile`
    sed -e "s/__SECRET_KEY__/$random_key/" < /usr/share/tweet-django/debian/settings.py.template > $tempfile
    chown root:www-data $tempfile
    chmod 0640 $tempfile
    ucf --debconf-ok $tempfile /etc/tweet-django/settings.py
    ucfr tweet-django /etc/tweet-django/settings.py 
    rm -f $tempfile

    chown -R www-data:www-data /var/log/tweet-django
    chown -R www-data:www-data /var/lib/tweet-django

    su --shell /bin/bash --login www-data --command "/usr/share/tweet-django/manage.py migrate"

    # dh_apache2 a2enconf tweet-django
fi

#DEBHELPER#
