#!/usr/bin/bash

source /usr/share/debconf/confmodule

# Borrowed from Debian.
_systemctl() {
	if [ -z "$DPKG_ROOT" ] && [ -d /run/systemd/system ]; then
		systemctl "$@" 1>&2
	else
		return 127
	fi
}

# Add `|| true' just to be safe, but this shouldn't be needed unless
# the package upgrade sequence is messed up (i.e., whilst updating
# OpenSSL, breaking systemd programs).
_systemctl daemon-reload || true

# Only preset these services for a fresh installation
# i.e. installing for the first time or after purging
if [ "$1" = configure ] && [ -z "$2" ]; then
	_systemctl preset nftables.service || true
	_systemctl preset firewalld.service || true
fi

if ([ "$1" = configure ] || [ "$1" = reconfigure ]); then
	db_fset firewalld/select_auto_reload seen false
	if _systemctl is-active --quiet firewalld; then
		db_get firewalld/select_auto_reload
		if [ "$RET" = "Discard all rules in-use and reload from disk" ]; then
			echo "Reloading firewalld immediately..." 1>&2
			firewall-cmd --reload 1>&2 || true
		elif [ "$RET" = "Save current rules in-use and reload from disk" ]; then
			echo "Saving and reloading firewalld..." 1>&2
			(firewall-cmd --runtime-to-permanent && firewall-cmd --reload) 1>&2 || true
		else
			echo "Not reloading firewalld..." 1>&2
		fi
	else
		echo "Firewalld isn't running - not reloading"
	fi
fi
