#!/bin/sh

set -eu

APP_NAME=userausfall
APP_USER=_$APP_NAME
APP_HOME=/var/lib/$APP_NAME
APP_ETC=/etc/$APP_NAME
APP_SETTINGS=$APP_ETC/settings.py
APP_PID=/var/run/uwsgi/app/$APP_NAME/pid
APP_UWSGI_CONFIG=/etc/uwsgi/apps-enabled/$APP_NAME.ini
APP_BACKUPS=/var/backups/$APP_NAME
APP_MEDIA=$APP_HOME/media
APP_CTL_SCRIPT="$APP_NAME"ctl

if [ "$1" = "configure" ]; then
    if ! getent passwd "$APP_USER" >/dev/null; then
        # adduser still recognizes usernames with leading underscores as bad name
        # even though the current debian packaging guidelines enforces this.
        adduser --quiet --system --group --disabled-password --force-badname \
            --home "$APP_HOME" "$APP_USER"
    fi

    if [ -f "$APP_UWSGI_CONFIG" ]; then
        if "$APP_CTL_SCRIPT" migrate --no-input >/dev/null; then
            rm -f "$APP_ETC/maintenance_mode"
        else
            echo "error while executing $APP_USER migrations. maintenance mode still active" >&2
        fi
    fi

    if [ -f "$APP_SETTINGS" ]; then
      chown "$APP_USER:" "$APP_SETTINGS"
    fi

    # create secure user dirs
    install -d -o "$APP_USER" -g nogroup -m 700 "$APP_BACKUPS"
    install -d -o "$APP_USER" -g "$APP_USER" -m 755 "$APP_MEDIA"

    "$APP_CTL_SCRIPT" collectstatic --no-input --clear

    if [ -f "$APP_PID" ]; then
        printf "reloading $APP_USER app server... "
        kill -HUP "$(cat "$APP_PID")" 2>/dev/null && echo "ok" || echo "failed"
    fi
fi

if [ "$1" = "triggered" ]; then
    "$APP_CTL_SCRIPT" collectstatic --no-input --clear
fi

set +eu

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

#DEBHELPER#

exit 0