#!/bin/bash
# integrate.sh - Linux desktop integration for Kaho (icon theme + .desktop entry).
#
# Idempotent and self-contained. Run on a fresh install (by install.sh) and after
# every update (by kaho_launcher), so an updated install ends up identical to a
# fresh one. It reads the icon theme from the Kaho data directory, which the
# update system delivers and refreshes like the binaries — so any integration
# step added here reaches existing installs on their next update.
#
# Shipped to the data dir as bin/kaho-integrate.
# Usage: kaho-integrate [DATA_DIR]
#   DATA_DIR defaults to ${XDG_DATA_HOME:-$HOME/.local/share}/kaho.

set -euo pipefail

XDG_DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
DATA_DIR="${1:-$XDG_DATA/kaho}"

log() { echo "[kaho-integrate] $*"; }

# Install every bundled icon size into the user's hicolor theme. 'Icon=kaho' in
# the desktop entry (and the Wayland app id) resolves through this theme.
install_icons() {
    local src_theme="$DATA_DIR/resources/icons/hicolor"
    local dest_theme="$XDG_DATA/icons/hicolor"
    if [[ ! -d "$src_theme" ]]; then
        return
    fi
    local installed=0 src rel dest
    while IFS= read -r -d '' src; do
        rel="${src#"$src_theme"/}"
        dest="$dest_theme/$rel"
        mkdir -p "$(dirname "$dest")"
        cp -f "$src" "$dest"
        chmod 644 "$dest"
        installed=$((installed + 1))
    done < <(find "$src_theme" -name 'kaho.png' -print0)
    if [[ "$installed" -gt 0 ]]; then
        log "Installed $installed icon size(s) into $dest_theme"
        if command -v gtk-update-icon-cache &>/dev/null; then
            gtk-update-icon-cache -f -t "$dest_theme" >/dev/null 2>&1 || true
        fi
    fi
}

# Write the application's desktop entry. Launches via kaho_launcher so pending
# updates apply first, and registers Kaho as a PDF / Markdown handler.
write_desktop_entry() {
    local apps_dir="$XDG_DATA/applications"
    local desktop_file="$apps_dir/kaho.desktop"
    mkdir -p "$apps_dir"
    cat > "$desktop_file" <<EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Kaho
GenericName=Document Viewer
Comment=Read and annotate PDF and Markdown documents
Icon=kaho
Exec="$DATA_DIR/bin/kaho_launcher" %F
Terminal=false
Categories=Office;Viewer;
Keywords=kaho;pdf;markdown;document;llm;
MimeType=application/pdf;text/markdown;text/x-markdown;
StartupNotify=true
StartupWMClass=kaho
EOF
    chmod 644 "$desktop_file"
    log "Wrote desktop entry: $desktop_file"
    if command -v update-desktop-database &>/dev/null; then
        update-desktop-database "$apps_dir" >/dev/null 2>&1 || true
    fi
}

install_icons
write_desktop_entry
