#!/bin/bash

ICONSIZES="$1 128 64 48 32" # icon search in given order
ICONPATHS="/usr/share/icons/hicolor /usr/share/pixmaps /usr/share/icons/gnome"

if [ "$1" = "--desktop" -o "$2" = "--desktop" ]; then
   DESKTOPCMD="yes"
else
   DESKTOPCMD=""
fi


# $1..$n = dir path with .desktop files
process_directories()
{
   while [ "$1" != "" ]; do

      for desktop in "$1"/*.desktop; do

         Name=
         Icon=
         Exec=
         Hidden=
         Terminal=

         while read LINE; do
            eval $LINE
         done <<< $(tac "$desktop" | egrep '^(Name|Icon|Exec|Hidden|Terminal)=' | sed -r "s/ *%.*//" | sed -r "s/=(.*)/='\\1'/")   #'

         if [ "$Hidden" = "true" ]; then
            continue
         fi

         for size in $ICONSIZES; do
            for ICONPATH in $ICONPATHS; do
               icon=$ICONPATH/$size"x"$size/apps/$Icon
               if [ -f "$icon".png ]; then Icon="$icon".png; break; fi
               if [ -f "$icon" ]; then Icon=$icon; break 2; fi
               icon=$ICONPATH/apps/$size"x"$size/$Icon
               if [ -f "$icon".png ]; then Icon="$icon".png; break; fi
               if [ -f "$icon" ]; then Icon=$icon; break 2; fi
               icon=$ICONPATH/$Icon
               if [ -f "$icon".png ]; then Icon="$icon".png; break; fi
               if [ -f "$icon" ]; then Icon=$icon; break 2; fi
            done
         done

         if [ "$DESKTOPCMD" != "" ]; then
            Exec="$desktop"
         fi

         if [ -e "$Icon" ]; then
            echo "$Name;$Icon;$Exec"
         fi

      done
   shift
   done
}

process_directories /usr/share/applications
