#!/bin/sh

case $1 in
  --bemenu)
    menu="bemenu -i -p launch -l 10"
    ;;
  --dmenu)
    menu="dmenu -i -p launch -l 10"
    ;;
  --fzf)
    menu="fzf -e --no-multi"
    ;;
  *)
    exit
    ;;
esac

# global
apps=$(/usr/bin/ls /usr/share/applications)
# local
if [ -d $HOME/.local/share/applications ]
then
  locals=$(/usr/bin/ls $HOME/.local/share/applications)
  apps=$(echo "$apps\n$locals")
fi
# flatpak
if command -v flatpak > /dev/null
then
  flatpaks=$(/usr/bin/ls $HOME/.local/share/flatpak/exports/share/applications | grep ".desktop")
  apps=$(echo "$apps\n$flatpaks")
  flatpak_sys=$(/usr/bin/ls /var/lib/flatpak/exports/share/applications | grep ".desktop")
  apps=$(echo "$apps\n$flatpak_sys")
fi

menu_desktop() {
  selected=$(echo "$apps" | ${menu} )
  if [ -f "/usr/share/applications/$selected" ]
  then
    nohup `grep '^Exec' "/usr/share/applications/$selected" | head -1 | sed 's/^Exec=//' | sed 's/%.//'` >/dev/null 2>&1&
  elif [ -f "$HOME/.local/share/applications/$selected" ]
  then
    nohup `grep '^Exec' "$HOME/.local/share/applications/$selected" | head -1 | sed 's/^Exec=//' | sed 's/%.//'` >/dev/null 2>&1&
  elif [ -f "$HOME/.local/share/flatpak/exports/share/applications/$selected" ]
  then
    nohup `grep '^Exec' "$HOME/.local/share/flatpak/exports/share/applications/$selected" | head -1 | sed 's/^Exec=//' | sed 's/%.//'` >/dev/null 2>&1&
  else
    nohup `grep '^Exec' "/var/lib/flatpak/exports/share/applications/$selected" | head -1 | sed 's/^Exec=//' | sed 's/%.//'` >/dev/null 2>&1&
  fi
}

menu_desktop
