#!/bin/bash
# add-to-personal-menu script to be called by app-select.conf to adds the selected App to the active personal menu
# BobC 12/29/2020 - credit to Dave
# adapted by ppc 22/5/2022 (fixed problem in adding to icewm's personal menu and no icewm is needed)

# This script should be located in /usr/local/bin
# a link to call it should be in /usr/lib/app-select/plugins
# it needs to be added to /usr/share/app-select/app-select.conf which will get copied to ~/.config/app-select.conf with the following line:

#Add to Personal menu|add-to-personal-menu "%p" "%n" "%e" "%i" "%t"

# %n = name of item
# %e = executable
# %c = categories
# %f = filename
# %p = filepath (name included)
# %t = terminal (true/false)
# %i = icon

echo "add-to-personal-menu 1:$1 2:$2 3:$3 4:$4 5:$5 xxxxx"
disp=${DISPLAY#:}
disp=${disp%.[0-9]}
wm=$(cat $HOME/.desktop-session/desktop-code.$disp | cut -d- -f2)
echo "active wm: $wm "
if [[ "$wm" == "icewm" ]]; then
	# IceWM window manager has personal menu in IceWM menu format at ~/.icewm/personal
	desktop_file=$1
	NOME=$2
	EXEC0=$3
	ICONE=$4
	TERME=$5
	#in case EXEC has more than one line, use only the first
	readarray -t lines < <(echo "$EXEC0")
	EXECperc="${lines[0]}"
	# See if terminal should be used, check for true regardless of case
	if fgrep -qix -- "$TERME" <<<"true"; then
		EXECperc="x-terminal-emulator -e $EXECperc"
	fi
	#add line to personal - the | cut -f1 -d"%"   part removes any %x option from the exec command.
	echo "prog "\"${NOME}"\" "${EXECperc}" "${ICONE}" "| cut -f1 -d"%"  >> ~/.icewm/personal
fi

if [[ "$wm" == "fluxbox" ]]; then
	desktop_file=$1
	NOME=$2
	EXEC0=$3
	ICONE=$4
	TERME=$5
	#in case EXEC has more than one line, use only the first
	readarray -t lines < <(echo "$EXEC0")
	EXECperc="${lines[0]}"
	# See if terminal should be used, check for true regardless of case
	if fgrep -qix -- "$TERME" <<<"true"; then
		EXECperc="x-terminal-emulator -e $EXECperc"
	fi
	#add line to personal - the | cut -f1 -d"%"   part removes any %x option from the exec command.
	#echo "prog "\"${NOME}"\" "${EXECperc}" "${ICONE}" "| cut -f1 -d"%"  >> ~/.fluxbox/personal
	echo \[exec\] \(${NOME}\) \{${ICONE}\} \<${EXECperc}\>| cut -f1 -d"%" >> ~/.fluxbox/personal
fi

if [[ "$wm" == "jwm" ]]; then
	desktop_file=$1
	NOME=$2
	EXEC0=$3
	ICONE=$4
	TERME=$5
	#in case EXEC has more than one line, use only the first
	readarray -t lines < <(echo "$EXEC0")
	EXECperc="${lines[0]}"
	# See if terminal should be used, check for true regardless of case
	if fgrep -qix -- "$TERME" <<<"true"; then
		EXECperc="x-terminal-emulator -e $EXECperc"
	fi
	#add line to personal - the | cut -f1 -d"%"   part removes any %x option from the exec command.
	#echo "prog "\"${NOME}"\" "${EXECperc}" "${ICONE}" "| cut -f1 -d"%"  >> ~/.fluxbox/personal
	sed -i '$ d' ~/.jwm/personal
	echo \<Program label=\"${NOME}\"  icon=\"${EXECperc}\"\>${ICONE}\<\/Program\> >> ~/.jwm/personal
	echo \<\/JWM\> >> ~/.jwm/personal
	jwm -reload
	fi
