#!/bin/sh
# postinst script for trutz-setup
#
# see: dh_installdeb(1)

set -e

# 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 https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

# True while a setup page from before the update steps left the setup waits in
# its step 3 (update of the setup): the position file was written by such an
# old backend (it carries no "step" name), holds the old step number 2, says
# that this step is not finished ("setup":false), and the setup service is up.
# A restart then cuts the page's connection in the middle of the wait; the old
# page gives up after a few failed attempts and stands still with "Weiter"
# greyed out (test VM, 11.10.2026). The old backend is left running instead:
# after its step 3 it restarts itself. A backend of this version writes the
# "step" name into the file at its start, so it is always restarted.
# Not for the old step 7 (number 6): there the old backend installs the
# packages itself and does not restart afterwards, and a page loaded again
# would be let through to the last step while packages are still installed.
old_page_waits_in_update_step() {
    [ -r /home/.tb/setupcache.json ] || return 1
    if grep -q '"step":' /home/.tb/setupcache.json; then
        return 1
    fi
    grep -Eq '"currentStep":2[,}]' /home/.tb/setupcache.json || return 1
    grep -q '"update":{"setup":false' /home/.tb/setupcache.json || return 1
    systemctl is-active --quiet trutz-setup
}

case "$1" in
    configure)
        # only run this if the trutzbox setup was not finished
        if [ -e /etc/comidio/trutzbox-status ]; then
            . /etc/comidio/trutzbox-status
            if [ "${firstBoot:-true}" = "true" ]; then
                # enable without a reload of its own, then ONE daemon-reload: it
                # loads the enable link and the unit file of this version before
                # the restart below. A plain "systemctl enable" makes systemd
                # reload all unit files a second time.
                systemctl enable --no-reload trutz-setup
                systemctl daemon-reload

                # Check if trutz-setup is currently updating itself
                # If the flag file exists, skip restart to prevent killing the update process
                # (only a setup backend from before the update steps left the
                # setup still writes the flag, during its own self-update; this
                # version installs no packages and is simply restarted)
                if [ -e /var/run/trutz-setup-updating ]; then
                    :
                elif old_page_waits_in_update_step; then
                    echo "trutz-setup: an old setup page waits in an update step, the setup service is not restarted now"
                    touch /run/trutz-setup-keep-running
                else
                    if systemctl is-active --quiet nginx; then
                        systemctl restart trutz-setup || exit $?
                    else
                        systemctl start trutz-setup || exit $?
                    fi
                fi

                # Create symlink only if it doesn't exist (idempotent)
                if [ ! -e /etc/nginx/apps-enabled ]; then
                    mkdir -p /etc/nginx/apps-enabled
                    ln -s /etc/nginx/apps-available/trutz-setup.conf /etc/nginx/apps-enabled/trutz-setup.conf
                elif [ ! -e /etc/nginx/apps-enabled/trutz-setup.conf ]; then
                    ln -s /etc/nginx/apps-available/trutz-setup.conf /etc/nginx/apps-enabled/trutz-setup.conf
                fi

                if systemctl is-active --quiet nginx; then
                    systemctl reload nginx || systemctl restart nginx || exit $?
                else
                    systemctl start nginx || exit $?
                fi

            fi;
        fi;
    ;;

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

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

# Check if trutz-setup was updating itself
# If so, exit before DEBHELPER runs to prevent service restart
# (The update.ts code of that old backend will send completion signals and handle restart manually)
if [ -e /var/run/trutz-setup-updating ]; then
    exit 0
fi
# Same for the restart skipped above for an old page waiting in an update step.
if [ -e /run/trutz-setup-keep-running ]; then
    rm -f /run/trutz-setup-keep-running
    exit 0
fi

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

#DEBHELPER#

exit 0
