#!/bin/sh
set -e

case "$1" in
    configure)
        # Create storage directory with correct ownership and permissions
        install -d -m 0700 -o root -g root /var/lib/age-verification
        install -d -m 0700 -o root -g root /var/lib/age-verification/device

        # Ensure config dir exists
        install -d -m 0755 /etc/age-verification

        # Secure the ages.conf if it already exists from a previous install
        if [ -f /var/lib/age-verification/ages.conf ]; then
            chown root:root /var/lib/age-verification/ages.conf
            chmod 0600 /var/lib/age-verification/ages.conf
        fi

        # Reload D-Bus so it picks up the new policy file
        if [ -d /run/dbus ] && [ -S /run/dbus/system_bus_socket ]; then
            dbus-send --system \
                      --type=method_call \
                      --dest=org.freedesktop.DBus \
                      /org/freedesktop/DBus \
                      org.freedesktop.DBus.ReloadConfig 2>/dev/null || true
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

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

# Enable and start the systemd service if systemd is running
if [ -d /run/systemd/system ]; then
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl enable age-verification-daemon.service >/dev/null 2>&1 || true
    systemctl start age-verification-daemon.service >/dev/null 2>&1 || true
fi

#DEBHELPER#

exit 0
