#!/bin/sh
# FIPS post-install script for Debian/Ubuntu
set -e

case "$1" in
    configure)
        # Create fips system group for control socket access
        if ! getent group fips >/dev/null 2>&1; then
            groupadd --system fips
        fi

        # Seed /etc/fips/fips.yaml from the shipped example only if it
        # does not already exist. The live config is no longer a dpkg
        # conf-file; this copy-if-absent yields to any operator- or
        # configuration-management-rendered file and never clobbers it.
        if [ ! -e /etc/fips/fips.yaml ]; then
            install -m 600 -o root -g root \
                /usr/share/fips/fips.yaml.example \
                /etc/fips/fips.yaml
        fi

        # Drop-in directory for operator nftables rules included by
        # /etc/fips/fips.nft. Empty by default; the include glob matches
        # nothing cleanly out of the box.
        if [ ! -d /etc/fips/fips.d ]; then
            mkdir -p /etc/fips/fips.d
            chmod 755 /etc/fips/fips.d
        fi

        # Ensure runtime directory exists with correct ownership
        if [ -d /run/systemd/system ]; then
            systemd-tmpfiles --create /usr/lib/tmpfiles.d/fips.conf 2>/dev/null || true
        fi

        # Reload systemd and enable services. fips-firewall.service is
        # intentionally NOT enabled here — operators opt in explicitly
        # with `systemctl enable --now fips-firewall.service`. See
        # /usr/share/doc/fips/fips-security.md for the rationale.
        if [ -d /run/systemd/system ]; then
            systemctl daemon-reload
            systemctl enable fips.service 2>/dev/null || true
            systemctl enable fips-dns.service 2>/dev/null || true

            # On upgrade, restart services that were running before
            if [ -n "$2" ]; then
                systemctl start fips.service 2>/dev/null || true
                if systemctl is-enabled --quiet fips-dns.service 2>/dev/null; then
                    systemctl start fips-dns.service 2>/dev/null || true
                fi
            fi
        fi
        ;;
esac

#DEBHELPER#

exit 0
