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

set -e

NAME=authentic2-multitenant
MANAGE_SCRIPT=$NAME-manage
AUTHENTIC_USER=authentic-multitenant
AUTHENTIC_GROUP=authentic-multitenant
AUTHENTIC_HOME=/var/lib/$NAME
AUTHENTIC_SECRET_KEY="/etc/$NAME/secret"

case "$1" in
    configure)
        if ! getent group $AUTHENTIC_GROUP > /dev/null 2>&1; then
            echo -n "Adding group $AUTHENTIC_GROUP.." >&2
            addgroup --quiet --system $AUTHENTIC_GROUP
            echo "..done" >&2
        fi
        if ! getent passwd $AUTHENTIC_USER > /dev/null 2>&1; then
            echo -n "Adding user $AUTHENTIC_USER.." >&2
            adduser --quiet --system --gecos "Authentic2 daemon" \
                    --ingroup $AUTHENTIC_GROUP \
                    --no-create-home --home $AUTHENTIC_HOME \
                    $AUTHENTIC_USER
            echo "..done" >&2
        fi
        if [ ! -f $AUTHENTIC_SECRET_KEY ]; then
            echo -n "Generating a secret key.." >&2
            echo -n "`</dev/urandom tr -dc [:alnum:]-_\!\%\^:\; | head -c70`" > "$AUTHENTIC_SECRET_KEY"
            chmod 0640 $AUTHENTIC_SECRET_KEY
            chown root:$AUTHENTIC_USER $AUTHENTIC_SECRET_KEY
            echo "..done" >&2
        fi
        chown $AUTHENTIC_USER:$AUTHENTIC_GROUP $AUTHENTIC_HOME/tenants \
            /var/lib/$NAME/collectstatic \
            /var/run/$NAME \
            /var/log/$NAME
        /etc/init.d/$NAME update
        ;;
    triggered)
        su -s /bin/sh -c "$MANAGE_SCRIPT hobo_deploy --redeploy" $AUTHENTIC_USER
        ;;
    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
