#!/bin/sh
# preinst script for wsssh-server

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

WSSSHD_RUNNING=0

case "$1" in
    install|upgrade)
        # Check if wssshd service is running before upgrade
        if [ -x /etc/init.d/wssshd ]; then
            if /etc/init.d/wssshd status >/dev/null 2>&1; then
                WSSSHD_RUNNING=1

                # Check if we're in a non-interactive environment
                if [ -n "$DEBIAN_FRONTEND" ] && [ "$DEBIAN_FRONTEND" = "noninteractive" ]; then
                    echo "Non-interactive environment detected, stopping wssshd service automatically..."
                    /etc/init.d/wssshd stop || true
                    sleep 2
                else
                    # Use debconf to ask user for confirmation
                    . /usr/share/debconf/confmodule
                    db_input medium wsssh-server/stop-service || true
                    db_go || true

                    # Get the user's answer
                    db_get wsssh-server/stop-service
                    if [ "$RET" = "true" ] || [ -z "$RET" ]; then
                        echo "Stopping wssshd service for upgrade..."
                        /etc/init.d/wssshd stop || true
                        # Give it a moment to fully stop
                        sleep 2
                    else
                        echo "User declined to stop wssshd service. Upgrade may fail."
                        echo "You can manually stop the service with: sudo /etc/init.d/wssshd stop"
                        echo "Then retry the upgrade."
                        exit 1
                    fi
                fi
            fi
        fi
    ;;

    abort-upgrade)
    ;;

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

# Store the running state for postinst
if [ "$WSSSHD_RUNNING" = "1" ]; then
    echo "WSSSHD_WAS_RUNNING=1" > /tmp/wsssh-server-upgrade-state
else
    echo "WSSSHD_WAS_RUNNING=0" > /tmp/wsssh-server-upgrade-state
fi

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

#DEBHELPER#

exit 0