#!/bin/bash
# ClamUI post-installation script
# Updates desktop database and icon cache after package installation

set -e

# postinst script for clamui
#
# See https://www.debian.org/doc/debian-policy/ for policy details
#
# Actions:
#   configure       - Package is being configured
#   abort-upgrade   - Failed upgrade, reverting
#   abort-remove    - Failed removal during upgrade
#   abort-deconfigure - Dependency issue during deconfigure

case "$1" in
    configure)
        # Update desktop file database
        # This registers the .desktop file with the system
        if command -v update-desktop-database > /dev/null 2>&1; then
            update-desktop-database -q /usr/share/applications || true
        fi

        # Update GTK icon cache
        # This makes the application icon available to the desktop environment
        if command -v gtk-update-icon-cache > /dev/null 2>&1; then
            gtk-update-icon-cache -q -t -f /usr/share/icons/hicolor || true
        fi

        # Force desktop menu refresh for running sessions
        # This helps icons appear without requiring logout/login
        if command -v xdg-desktop-menu > /dev/null 2>&1; then
            xdg-desktop-menu forceupdate --mode system 2>/dev/null || true
        fi

        # KDE Plasma cache rebuild (if applicable)
        if command -v kbuildsycoca5 > /dev/null 2>&1; then
            kbuildsycoca5 --noincremental 2>/dev/null || true
        fi
        if command -v kbuildsycoca6 > /dev/null 2>&1; then
            kbuildsycoca6 --noincremental 2>/dev/null || true
        fi

        # Cinnamon desktop: reload theme to refresh menu icons
        # Cinnamon caches icons separately from GTK and needs explicit reload
        if command -v dbus-send > /dev/null 2>&1; then
            # Signal Cinnamon to reload its theme (includes icon refresh)
            dbus-send --session --dest=org.Cinnamon --type=method_call \
                /org/Cinnamon org.Cinnamon.ReloadTheme 2>/dev/null || true
        fi

        # Touch the desktop file to trigger file monitor refresh
        # Some DEs watch for mtime changes on desktop files
        if [ -f /usr/share/applications/io.github.linx_systems.ClamUI.desktop ]; then
            touch /usr/share/applications/io.github.linx_systems.ClamUI.desktop 2>/dev/null || true
        fi
        ;;

    abort-upgrade|abort-remove|abort-deconfigure)
        # Nothing to do on abort
        ;;

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

exit 0
