#!/bin/bash

getIcon() {
    local desktop=""
    
    # Search for desktop files by WM class
    if [ -n "$1" ]; then
        desktop=$(grep -l "StartupWMClass.*$1$" /usr/share/applications/*.desktop)
        [ -z "$desktop" ] && desktop=$(grep -Pl "Name\s*=\s*$1$" /usr/share/applications/*.desktop)
        [ -z "$desktop" ] && desktop=$(ls /usr/share/applications/${1}.desktop 2>/dev/null)
    fi
    
    # If not found by WM class, search by process name
    if [ -z "$desktop" ] && [ -n "$2" ]; then
        desktop=$(pgrep -fl "$2" | awk '{print $2}' | grep -m1 -o '[^/]*\.desktop' | head -n1)
        [ -n "$desktop" ] && desktop="/usr/share/applications/$desktop"
    fi
    
    # If not found by WM class or process name, search by name or description
    if [ -z "$desktop" ] && [ -n "$1" ]; then
        desktop=$(grep -Pl "$1" /usr/share/applications/*.desktop)
    fi
    
    echo "$desktop"
}

desktop=$(getIcon "$1" "$2")
if [ -n "$desktop" ]; then
    image=$(awk -F'[[:space:]]*=[[:space:]]*' '/Icon[[:space:]]*=/ && !seen[$2]++ {print $2; exit}' "$desktop")
    icon="/usr/share/icons/Papirus-Dark/128x128/apps/${image}.svg"
    echo -n "$icon"
fi
