#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2021"
app="$(basename $0)"
msgid="The Starbuntu application
<i>\$app</i>
was written by"
info="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"

yad --center --fixed --title="$title" --window-icon="info" --image="info" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year"$'\n' --text-align=center --selectable-labels --button="OK" &
wunwa "$title" > /dev/null; xdotool key Home key Down
}

search="$1"
[ "$search" = "info" ] && Info && exit 0

cd $HOME/.config/menus
dms=($(dims)); vert=${dms[0]#*|}; ((vert=vert-96))
title1=$"GUI Application Search"
title2=$"Found GUI Application(s):"
ask=$"Which GUI-App? Partial key word will do!"
msg=$"Nothing found!"
cancel=$"Cancel"

IFS=$'\n'
if [ -z "$search" ];then
    search=$(yad --center --title="$title1" --text="$ask" --window-icon="$HOME/.icons/binoculars.png" --borders=20 --entry --button="$cancel":1 --button="Info":"$0 info" --button="OK":0)
    button=$?
else
    button=0
fi

if [ $button -eq 0 ]; then
    found=($(grep -ris --exclude="Apps.lst" "$search[^‖]*$"))
    found=(${found[@]#*‖})
    length=${#found[@]}
    for ((k=0; k<length; k++)); do found[$k]="${found[$k]#*‖}  §${found[$k]%‖*}  § "; done
    found_sorted=($(sort <<< "${found[*]}"))
    IFS=$'\n§'
    found=(${found_sorted[@]})
    found=(${found[@]//\&/\&amp;})
#    echo "${found[*]}"; exit
    if [ $length -gt 0 ]; then
	height=$((length*24+80))
	[ $height -gt $vert ] && height=$vert
	app=$(yad --center --title="$title2" --window-icon="$HOME/.icons/binoculars.png" --width=800 --height=$height --list --expand-column=0 --regex-search --separator="§" --ellipsize-cols=2 --ellipsize=END --editable --editable-cols=3 --column=$" Label: " --column=$" Command: ""			" --column=$" Parameters:  ""			" ${found[@]} --search-column=1 --regex-search --button="$cancel":1 --button="Info":"$0 info" --button="OK":0)
	if [ $? -eq 0 ]; then
	    app=${app::-1}
	    label="${app%%§*}"
	    app="${app#*§}"
	    params="${app##*§}"
	    params="${params// /\\ }"
	    app="${app%§*}"
	    app="${app//amp;/}"
	    [ "${label::1}" = "▶" ] && app="multimenu $(echo -n $app | xargs).lst"
	    if [[ "$app" =~ \%[fFuU] ]]; then
	        [ "$params" = "\ " ] && params=""
	        [[ "$params" =~ "@" ]] && sep="|" || sep="@"
	        app="$(echo "$app" | sed -E "s$sep([^\\])\%[fFuU]$sep\1$params$sep")"
	    fi
	    eval "$app &"
	fi
    else
	yad --center --title="$title1" --window-icon="$HOME/.icons/binoculars.png" --image=dialog-warning --borders=10 --text=$'\n'$'\t'"$msg"$'\t'$'\n' --button="OK":0 
    fi
fi
