#!/bin/sh
#
# Postinst script for docbow
#

set -e

NAME=docbow
USER=$NAME
GROUP=$NAME
HOME=/var/lib/$NAME

case "$1" in
    configure)
        if ! getent group $GROUP > /dev/null 2>&1; then
            echo -n "Adding group $GROUP.." >&2
            addgroup --quiet --system $GROUP
            echo "..done" >&2
        fi
        if ! getent passwd $USER > /dev/null 2>&1; then
            echo -n "Adding user $USER.." >&2
            adduser --quiet --system --gecos "$NAME daemon" \
                    --ingroup $GROUP \
                    --no-create-home --home $HOME \
                    $USER
            echo "..done" >&2
        fi
        if [ ! -f "/etc/$NAME/secret" ]; then
            echo -n "Generating Django secret.." >&2
            echo "export SECRET_KEY='`</dev/urandom tr -dc [:alnum:]-_\!\%\^:\; | head -c70`'" > /etc/$NAME/secret
            chmod 0640 /etc/$NAME/secret
            chown root:$GROUP /etc/$NAME/secret
            echo "..done" >&2
        fi

        if [ ! -f "/etc/$NAME/db" ]; then
            cat > /etc/$NAME/db <<EOC
export DATABASE_ENGINE='django.db.backends.postgresql_psycopg2'
export DATABASE_NAME='docbow'
export DATABASE_USER='docbow'
export DATABASE_PASSWORD='SOME_PASSWORD'
export DATABASE_HOST='localhost'
EOC
        fi

        chown $USER:$GROUP /var/lib/docbow \
            /var/lib/docbow/static \
            /var/lib/docbow/collectstatic \
            /var/lib/docbow/templates \
            /var/lib/docbow/media \
            /var/run/docbow \
            /var/log/docbow
        ;;

    reconfigure|abort-upgrade|abort-remove|abort-deconfigure)
        ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
