#!/bin/sh
# Copyright 2026 Petri Koistinen. Licensed under the Apache License, Version 2.0.
#
# postinst of refineid-pkcs11. The packaging script fills in @MODULE@.
set -e

MODULE="@MODULE@"
# Ubuntu's Firefox snap cannot load a module from the host's /usr/lib:
# its confinement denies the path, a symlink included, so the module is
# copied into the snap's common data directory and the Firefox policy
# names both paths. Every configure refreshes the copy.
SNAP_COMMON="/var/snap/firefox/common"
SNAP_DIR="$SNAP_COMMON/refineid"

case "$1" in
    configure)
        if command -v ldconfig >/dev/null 2>&1; then
            ldconfig
        fi
        if [ -d "$SNAP_COMMON" ]; then
            install -d -m 755 "$SNAP_DIR"
            install -m 644 "$MODULE" "$SNAP_DIR/librefineid_pkcs11.so"
            # The snap reaches pcscd only through its pcscd interface,
            # which some Ubuntu releases leave unconnected; without it
            # the module loads inside the snap but sees no reader.
            if command -v snap >/dev/null 2>&1; then
                snap connect firefox:pcscd >/dev/null 2>&1 || true
            fi
        fi
        if [ -d /run/systemd/system ]; then
            if systemctl is-active --quiet polkit 2>/dev/null; then
                systemctl reload polkit 2>/dev/null || true
            fi
            systemctl enable --now pcscd.socket 2>/dev/null \
                || systemctl enable --now pcscd 2>/dev/null \
                || true
        fi
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

exit 0
