#!/usr/bin/env bash

getIcon() {
    local desktop=""
    
    # Search for desktop files by WM class
    if [ -n "$1" ]; then
        desktop=$(grep -l "StartupWMClass.*$1$" /run/current-system/sw/share/applications/*.desktop)
        [ -z "$desktop" ] && desktop=$(grep -Pl "Name\s*=\s*$1$" /run/current-system/sw/share/applications/*.desktop)
        [ -z "$desktop" ] && desktop=$(ls /run/current-system/sw/share/applications/"${1}".desktop 2>/dev/null)
    fi
    
    # If not found by WM class, search by process name
    if [ -z "$desktop" ] && [ -n "$2" ]; then
        process=$(ps -p "${2}" -o comm=)
        desktop=$(grep -Pl "$process" /run/current-system/sw/share/applications/*.desktop)
        [ -n "$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" /run/current-system/sw/share/applications/*.desktop)
    fi
    
    echo "$desktop"
}

desktop=$(getIcon "$1" "$2")
if [ -n "$desktop" ]; then
    desktop=$(echo "$desktop" | awk 'NR==1')
    icon=$(awk -F'[[:space:]]*=[[:space:]]*' '/Icon[[:space:]]*=/ && !seen[$2]++ {print $2; exit}' "$desktop")
    echo -n "${icon}.svg"
fi
