#!/bin/sh
# postinst script
#
# see: dh_installdeb(1)

set -e
APP_ID="${DPKG_MAINTSCRIPT_PACKAGE:?DPKG_MAINTSCRIPT_PACKAGE is not set as it should be}"
RUN_AS="$APP_ID"

. "/etc/default/$APP_ID"

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

case "$1" in
    configure)
        if ! getent passwd "$RUN_AS" >/dev/null; then
            adduser --quiet --system --ingroup daemon --no-create-home \
                    --home "/var/opt/$APP_ID" --shell /usr/sbin/nologin "$RUN_AS"
            usermod -a -G shadow "$RUN_AS"
        fi
        if test -f /etc/jupyterhub/banner.png; then
            # Original banner is 208x56
            ( umask 0022 && \
              cat /etc/jupyterhub/banner.png >/opt/venvs/jupyterhub/share/jupyterhub/static/images/jupyter.png )
        fi
    ;;

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

    triggered)
    ;;

    *)
        echo "${DPKG_MAINTSCRIPT_PACKAGE}: 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#

# Protect configuration files (possibly containing passwords)
chmod 0640 /etc/"$APP_ID"/*.py
chgrp daemon /etc/"$APP_ID"/*
chmod 0440 /etc/sudoers.d/"$APP_ID"

# System user's directory permissions
chown -RPh "$RUN_AS".daemon /var/log/"$APP_ID"/. /var/opt/"$APP_ID"/.

# Start service AFTER permissions etc. are fixed
if [ "$1" = "configure" ]; then
    if "${JUPYTERHUB_AUTO_RESTART:-false}"; then
        echo "*** $APP_ID: Starting service..."
        systemctl daemon-reload
        systemctl start "$APP_ID" \
            || echo >&2 "!!! $APP_ID: Starting service failed (RC=$?), for details see journalctl"
    fi
fi

exit 0
