#!/bin/sh
# prerm for multiportal. Stop the scheduler, queue workers and websocket proxy
# before the payload is removed or replaced. On upgrade the services stay down
# until mpctl migrates and starts them again (see postinst), so no execution
# surface - scheduler included - runs new code against an un-migrated schema.
set -e

stop_unit() {
    if command -v deb-systemd-invoke >/dev/null 2>&1; then
        deb-systemd-invoke stop "$1" >/dev/null 2>&1 || true
    else
        systemctl stop "$1" >/dev/null 2>&1 || true
    fi
}

case "$1" in
    remove|upgrade|deconfigure)
        # On remove only: drop the postinst-created web symlinks. dpkg does not
        # own them, so leaving them behind orphans the whole payload tree. On
        # upgrade they must survive - php-fpm keeps serving assets through them
        # and the new postinst re-checks them anyway.
        if [ "$1" = "remove" ]; then
            for link in assets iso uploads; do
                linkpath="/usr/share/multiportal/backend/web/$link"
                [ -L "$linkpath" ] && rm -f "$linkpath"
            done
        fi
        if [ -d /run/systemd/system ]; then
            stop_unit multiportal-cron.timer
            stop_unit multiportal-cron.service
            # Glob stop so systemd parallelises draining instances; generous
            # TimeoutStopSec in the unit lets in-flight Proxmox jobs finish.
            stop_unit 'multiportal-queue@*.service'
            stop_unit multiportal-websocket.service
        fi
        ;;
    failed-upgrade)
        ;;
esac

exit 0
