#!/bin/bash
#pRun 1.7.2
#Functions (radky)

export TEXTDOMAIN=prun
export OUTPUT_CHARSET=UTF-8

case "$1" in
#Search
-prun_search)
	searchALL=$(cat $WORKDIR/preferences/search_all)
	if [ "$searchALL" = "true" ]; then
	 searchMODE=""
	else
	 searchMODE="^"
	fi
	searchPATTERN=$(grep -aEi "$searchMODE$entryPRUNAPP" /tmp/PR-search)
	if [ "$searchPATTERN" ]; then
	 echo "$searchPATTERN" | sort -fu > /tmp/PR-apps #update /tmp/PR-apps
	else
	 echo > /tmp/PR-apps
	fi
	;;

#Launch
-basic_launch) #launch button or double-click
	PRUNAPP=$(cat /tmp/PR-selectedAPP)
	searchTEXT="$PRUNAPP"
	. $WORKDIR/func -launch
	;;

-entry_launch) #search module
	PRUNAPP=$(cat /tmp/PR-selectedAPP)
	PRUNAPP2=$(head -n 1 /tmp/PR-apps 2>/dev/null)
	searchTEXT="$PRUNAPP"
	[ ! "`which $PRUNAPP`" ] && PRUNAPP="$PRUNAPP2"
	. $WORKDIR/func -launch
	;;

-history_launch) #history module
	PRUNAPP=$(cat /tmp/PR-hxAPP)
	searchTEXT="$PRUNAPP"
	[ "$searchTEXT" = "" ] && searchTEXT="$(gettext 'Please try again')"
	. $WORKDIR/func -launch
	;;

-launch)
	TERMINAL=$(cat $WORKDIR/preferences/terminal_launch)
	if [ ! "`which $PRUNAPP`" ]; then
	  Xdialog --title $(gettext 'Error') --msgbox "\n          ""– $searchTEXT –""          \n\n          $(gettext 'Invalid selection or item not found!')          \n" 0 0 exit 0
	else
	  if [ "$TERMINAL" = "true" ]; then
	    if [ "$CLOSE_TERMINAL" = "true" ]; then
	      $TERM -e $PRUNAPP &
	    else
	      echo '#!/bin/sh' > /tmp/Terminal
	      echo "$PRUNAPP"  >> /tmp/Terminal
	      echo 'echo' >> /tmp/Terminal
	      echo 'echo -n "$(gettext "PRESS ENTER KEY TO CLOSE TERMINAL...") "' >> /tmp/Terminal
	      echo 'read fauxhold' >> /tmp/Terminal
	      chmod +x /tmp/Terminal
	      exec $TERM -e /tmp/Terminal &
	    fi
	  else
	    $PRUNAPP &
	  fi
	fi
	echo -e "$PRUNAPP" >> $WORKDIR/PR-history #add menu item to launch history
	tac $WORKDIR/PR-history | awk '!a[$0]++' | tac | sed '/^$/d' | tail -n50 > /tmp/tmp ; mv -f /tmp/tmp $WORKDIR/PR-history #remove duplicate menu items and blank lines in launch history
	if [ "$CLOSE_PRUN" = "true" ]; then
	 if [ "`which busybox`" ]; then
	  prunPID=$(busybox ps | grep -aE 'PRUN_DIALOG|prun' | grep -aEv 'grep|geany|gedit|leafpad|medit|mousepad|nicoedit' | awk '{print $1}')
	 else
	  prunPID=$(ps -ax | grep -aE 'PRUN_DIALOG|prun' | grep -aEv 'grep|geany|gedit|leafpad|medit|mousepad|nicoedit' | awk '{print $1}')
	 fi
	 kill -9 $prunPID
	fi
	;;

-launchhistory_clear)
	Xdialog --title "pRun $(gettext 'History')" --under-mouse --cancel-label "No" --ok-label "Yes"  --yesno "\n     $(gettext 'Start new launch history?')     \n\n     $(gettext 'This will delete the current history.')     \n" 0 0
	if [[ $? == 0 ]]; then
	  rm -f $WORKDIR/PR-history 2>/dev/null
	fi
	/tmp/PR-history &
	;;

esac
