#!/bin/sh
set -e

PACKAGE="$DPKG_MAINTSCRIPT_PACKAGE"

case "$1" in
    configure)

        # Create group if not existing
        getent group $PACKAGE || groupadd $PACKAGE

        # Create user if not existing
        if ! id $PACKAGE > /dev/null 2>&1 ; then
            adduser --system --home /srv/$PACKAGE --no-create-home \
                --ingroup $PACKAGE --disabled-password --shell /bin/bash \
                $PACKAGE
        fi

        # Create log directory
        if [ ! -e /var/log/$PACKAGE ]; then
            mkdir /var/log/$PACKAGE
        fi

        # Create config directory
        if [ ! -e /etc/$PACKAGE ]; then
            mkdir /etc/$PACKAGE
        fi

        # Make sure user owns his directories
        chown -R $PACKAGE:$PACKAGE /srv/$PACKAGE
        chown -R $PACKAGE:$PACKAGE /var/log/$PACKAGE
        chown -R $PACKAGE:$PACKAGE /etc/$PACKAGE

        # Install web application as service
        update-rc.d -f $PACKAGE defaults

        # (re)start service
        service $PACKAGE restart
    ;;

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

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

exit 0
