#!/bin/bash
PROCID=$1
LAUNCHER=""
if [[ $(readlink /proc/$PROCID/exe) == /Applications/* ]]; then
	if [[ -f "/usr/share/applications/$(readlink /proc/$PROCID/exe | sed "s+/Applications/.++g" | sed "s+/.*++g").napp.desktop" ]]; then
		LAUNCHER="/usr/share/applications/$(readlink /proc/$PROCID/exe | sed "s+/Applications/.++g" | sed "s+/.*++g").napp.desktop"
	fi
else
	app_id=$PROCID
	executed=$(ps -p $app_id -o comm= | sed 's#/.*##' | sed 's/-$//')
	desktop_file_path=$(find /usr/share/applications -name "*.desktop" -type f -exec bash -c '
	  desktop_file=$1
	  exec_line=$(grep -Po "^Exec='$executed'" "$desktop_file")
	  no_display_value=$(grep -Po "(?<=NoDisplay=)[^ ]+" "$desktop_file")
	  if [[ -n $exec_line && $no_display_value != "true" ]]; then
	    echo "$desktop_file"
	  fi
	' _ {} \;)
	if [ -z "$desktop_file_path" ]; then
	  ErrorText="Cannot pin the application launcher: No such file or directory..\n\nDon't forget, we're trying to fix errors and bugs like this and we can't give true time.\n\nTechnical Info: PROCID=$1"
	  if LANG="tr_TR.UTF-8"; then
	  	ErrorText="Uygulama başlatıcısı işaretlenemiyor: Böyle bir dosya ya da dizin yok.\n\nUnutmayın, gelecek yamalarda bu tarz hataları çözmek için çalışıyoruz ancak ne zaman çözüleceği konusunda kesin zaman veremeyiz.\n\nTeknik Bilgi: PROCID=$1"
	  fi
	  zenity --error --text="$ErrorText"
	  exit 1
	else
	  LAUNCHER=$desktop_file_path
	  LAUNCHER=$(echo $LAUNCHER | sed 's/ .*//')
	fi
fi
echo $LAUNCHER >> ~/.config/awesome/widget/pinned-apps/apps.txt
