#!/bin/sh

set -e

# Check if systemd is supported (not a container)
CMDLINE=$(tr -d '\0' < /proc/1/cmdline)
if [ ! -z "${CMDLINE##*system*}" ] && [ ! -z "${CMDLINE##*init*}" ]; then
  exit 0
fi

. /usr/share/debconf/confmodule

check_upgrade_declined()
{
	db_get ntopng/license_expired_continue_installation
	if [ "$RET" = false ]; then
	    if [ "$1" = "warn" ]; then
		echo "WARNING: Maintenance expired. Upgrade declined by the user." >&2
	    fi
	    exit 1
	fi
}

prompt_license_expired()
{
    local NOW=`date +'%s'`
    local EXPIRY_EPOCH=`/usr/bin/@APP@ --check-maintenance | cut -d' ' -f 1`

    # always re-ask the question
    db_reset ntopng/license_expired_continue_installation || true
    if [ "${EXPIRY_EPOCH}" = "Invalid" ]; then
	# Missing or invalid (e.g., expired demo) license.
	# Permanent licenses are always valid even when the maintenance is expired.
	:
    elif echo "${EXPIRY_EPOCH}${NOW}" | grep -q "^[0-9]\+$"; then
	if [ "${EXPIRY_EPOCH}" -gt "0" ] && [ "${EXPIRY_EPOCH}" -lt "${NOW}" ]; then
	    db_input high ntopng/license_expired_continue_installation || true
	    db_go || true
	    check_upgrade_declined
	fi
    fi
}

# Only shut the daemon down if we're really removing the package.  If this is
# an upgrade, we will instead do a restart in the postinst... this keeps ntopng
# from being left shut down for a long time, which could pose problems.
case "$1" in
	failed-upgrade)
		check_upgrade_declined warn
	;;

	*)
	if [ "$1" = "upgrade" ]; then prompt_license_expired; fi
	echo "Stopping @APP@ services..."
	if hash systemctl 2>/dev/null; then
	    if hash deb-systemd-invoke 2>/dev/null; then
		deb-systemd-invoke stop ntopng
		deb-systemd-invoke stop 'ntopng@*'
                if [ ! "$1" = "upgrade" ] ; then
                    # Disable unless this is an upgrade
		    deb-systemd-invoke disable ntopng
		    #disable doesn't want the star after the @, it takes it automatically
		    deb-systemd-invoke disable 'ntopng@'
                fi
	    else
		systemctl stop ntopng
		systemctl stop 'ntopng@*' --all
                if [ ! "$1" = "upgrade" ] ; then
		    systemctl disable ntopng
		    #disable doesn't want the star after the @, it takes it automatically
		    systemctl disable 'ntopng@' --all
                fi
	    fi
	    systemctl daemon-reload
	    systemctl reset-failed
	elif [ -f /etc/init.d/ntopng ]; then
		/etc/init.d/ntopng stop
	fi
	;;
esac

exit 0
