#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2022"
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
}

tip () {
    rule1=$"No spaces"
    rule2=$"No special characters"
    rule3=$"First letter uppercase"
    alarm=$"Attention with the catgory identifier:"
    title=$"Category Rules"

    help1=$'\t'"    ⚫ $rule1"
    help2=$'\t'"    ⚫ $rule2"
    help3=$'\t'"    ⚫ $rule3"
    help="    $alarm    &#10;&#10;$help1&#10;$help2&#10;$help3&#10;"
    yad --center --fixed --title="$title" --window-icon="/usr/share/icons/gnome/48x48/status/dialog-warning.png" --image="/usr/share/icons/gnome/48x48/status/dialog-warning.png" --image-on-top --borders=20 --text="$help" --selectable-labels --button="OK" &
    wunwa "$title" > /dev/null; xdotool key Home key Down
}

param="$1"
[ "$param" = "info" ] && Info && exit 0
[ "$param" = "tip" ] && tip && exit 0

user=$(whoami)
if [[ "$user" != "root" ]]; then
    gsu --no-error-msg $0 $user & exit 0
fi

user="$1"
[ -z "$user" ] && user="$(id -nu 1000)"
casa="/home/$user"

IFS=$'\n'
f_menu="/etc/xdg/menus/gnome-applications.menu"

appmenu="$(grep 'directory' $f_menu)"
appmenu="$(echo "$appmenu" | sed 's/.directory//g; s/<Directory>//g; s/<\/Directory>//g; s/X-GNOME-Menu-Applications/AApps/g; /<!--/d')"
appmenu="${appmenu//$'\n'     /,     }"
appmenu="$(sort -b <<< "$appmenu")"
appmenu="${appmenu//, /$'\n' }"
appmenu=($appmenu)
l=${#appmenu[@]}
for ((k=1; k<l; k++)); do
    item="$(echo "${appmenu[$k]}" | sed 's/ *//g')"
    [ ! -f "$casa/.config/menus/$item.lst" ] && unset appmenu[$k]
done
appmenu=(${appmenu[@]})
appmenu_loc=(${appmenu[@]})
appmenu[0]="${appmenu[0]/AApps/Main Category}"
l=${#appmenu[@]}
[ "$LANGUAGE" = "en" ] && search="Name=" || search="Name\[$LANGUAGE.*="
for ((k=1; k<l; k++)); do
    item="$(echo "${appmenu_loc[$k]}" | sed 's/ *//g')"
    [[ "${appmenu_loc[$k]}" =~ " " ]] && pre="${appmenu_loc[$k]% *} " || pre=""
    [ -f "$casa/.local/share/desktop-directories/$item.directory" ] && item_loc="$(grep "$search" $casa/.local/share/desktop-directories/$item.directory)" || item_loc="$(grep "$search" /usr/share/desktop-directories/$item.directory)"
    if [ -z "$item_loc" ]; then
	[ -f "$casa/.local/share/desktop-directories/$item.directory" ] && item_loc="$(grep "Name=" $casa/.local/share/desktop-directories/$item.directory)" || item_loc="$(grep "Name=" /usr/share/desktop-directories/$item.directory)"
    fi
    appmenu_loc[$k]="$pre${item_loc#*=}" 
done
appmenu_loc="$(echo "${appmenu_loc[*]}")"
appmenu_loc="${appmenu_loc//$'\n'     /,     }"
appmenu_loc="$(sort -bu <<< "$appmenu_loc")"
appmenu_loc="${appmenu_loc//, /$'\n' }"
appmenu_loc="${appmenu_loc/AApps/"$(echo $"Main Category")"}"
appmenu_loc="${appmenu_loc//&/\&amp;}"
appmenu_loc=($appmenu_loc)

h=${#appmenu_loc[@]}; h=$(((h+11)*20))

title=$"Create or delete a category"
text="$(echo $"Select the place of the new category
resp. the category to be deleted:")"
deltext=$"Delete category"
oktext=$"Create category here"
cancel=$"Quit"

name=`yad --center --title="$title" --width=350 --height=$h --borders=20 --text="$text"$'\n' --list --no-headers --window-icon=format-indent-less-rtl --column="Categories" ${appmenu_loc[@]} --button="$cancel":1 --button="Del!!""$deltext":2 --button="Info":"$0 info" --button="OK!!""$oktext":0`
exit_code=$?

appmenu_loc=(${appmenu_loc[*]//&amp;/\&}); name="${name//&amp;/\&}"
[ $exit_code -eq 2 ] && del=true || del=false
if [ $exit_code -eq 0 ] || $del; then
    [[ "$name" =~ ^' ' ]] && pre="$(awk -F'[^ ]' '{print $1}' <<< $name)" || pre=""
    name="$(echo "$name" | sed 's/^ *//g; s/|//g')"
    if [ "$name" != "$(echo $"Main Category")" ]; then
	f_c=$(grep -lE "$search$name$" $casa/.local/share/desktop-directories/* | head -n 1)
	[ -z "$f_c" ] && f_c=$(grep -lE "$search$name$" /usr/share/desktop-directories/* | head -n 1)
	[ -z "$f_c" ] && f_c=$(grep -lE "Name=$name$" $casa/.local/share/desktop-directories/* | head -n 1)
	[ -z "$f_c" ] && f_c=$(grep -lE "Name=$name$" /usr/share/desktop-directories/* | head -n 1)
	ctg=$(basename "$f_c")
	ctg="${ctg%.*}"
    else
	ctg=$"Main Category"
	$del && text="$(echo $"&#10;    Main level not removable!&#10;")" && yad --center --title=$"Error" --fixed --window-icon=format-indent-less-rtl --image="dialog-warning" --borders=20 --text="$text" --button="OK" && exit 2
    fi
else
    exit $exit_code
fi

if ! $del; then
    text1=$"Place of category: "
    text2=$"Rules for category identifier"
    title1=$"Set category parameters"
    button0=$"Cancel"
    button1=$"Hints"
    button2=$"Help"
    field1=$"New Category&#58; "
    field2=$"Comment"
    field3=$"Icon: "
    cd /usr/share/icons/Humanity/categories/48/
    if [ "$LANGUAGE" != "en" ]; then
	lang_dir=$LANGUAGE
	field_name1="--field=Name[en]&#58; "\ ""
	field_name2="--field=Name[$LANGUAGE]&#58; "\ ""
	field_comment1="--field=$field2[en]&#58; "\ ""
	field_comment2="--field=$field2[$LANGUAGE]&#58; "\ ""
    else
	lang_dir="C"
	field_name1="--field=Name&#58; "\ ""
	field_name2=""
	field_comment1="--field=$field2&#58; "\ ""
	field_comment2=""
    fi
    name="${name//&/\&amp;}"
    entries=`yad --center --title="$title1" --width=600 --height=200 --window-icon="format-indent-less-rtl" --borders=10 --text="<b>$text1$name</b>" --text-align=center --form --separator="¦" --field="$field1" "" $field_name1 $field_name2 $field_comment1 $field_comment2 --field="$field3":SFL --file-filter $"Graphic Files "" | *.svg *.png *.SVG *.PNG" --add-preview --button="$button0":1 --button="$button2":"yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#create-rm-category" --button="$button1!!""$text2":"$0 tip" --button="Info":"$0 info" --button="OK":0`
    exit_code=$?
    [ $exit_code -gt 0 ] && exit $exit_code
    new_ctg="${entries%%¦*}"; entries="${entries#*¦}"
    new_name="${entries%%¦*}"; entries="${entries#*¦}"
    [ -z "$new_name" ] && new_name="$new_ctg"
    [ $LANGUAGE != "en" ] && new_name_loc="${entries%%¦*}" && entries="${entries#*¦}"
    [ -z "$new_name_loc" ] && new_name_loc="$new_name"
    new_comment="${entries%%¦*}"; entries="${entries#*¦}"
    [ $LANGUAGE != "en" ] && new_comment_loc="${entries%%¦*}" && entries="${entries#*¦}"
    new_icon="${entries%%¦*}"; entries="${entries#*¦}"
    if [ -z "$new_icon" ] || [ "${new_icon: -1}" = '/' ]; then new_icon="yad"; fi

    if [ -z "$new_ctg" ] || [[ ! "$new_ctg" =~ ^[A-Z][A-Za-z0-9_-]*$ ]]; then
	title=$"Warning"
	text=$"Entries incomplete or incorrect!"
	yad --center --fixed --title="$title" --window-icon="/usr/share/icons/gnome/48x48/status/dialog-warning.png" --image="/usr/share/icons/gnome/48x48/status/dialog-warning.png" --image-on-top --borders=20 --text="$text" --button="OK"
	exit 1
    fi
fi

applmenu=$(cat $f_menu)
to_find=">$ctg.directory"
[ "$ctg" = $"Main Category" ] && to_find="^</Menu>"
found="$(grep -n "$to_find" <<< $(echo "$applmenu"))"
n_found="${found%%:*}"; ((n_Begin=n_found-3)); ((n_Name=n_found-1)); ((n_End=n_found+6))
found="${found#*:}"
if $del; then
    End="$(sed "${n_End}q;d" <<< "$applmenu")"
    if [[ ! "$End" =~ "</Menu>" ]]; then
	title=$"Error"
	text=$"&#10;    The category has a sub-category,&#10;    so you cannot remove it!&#10;"
	yad --center --title="$title" --fixed --window-icon=format-indent-less-rtl --image="dialog-warning" --borders=20 --text="$text" --button="OK"
	exit 1
    fi
    pre="${pre::-2}"
    new_name="$(grep "Name=" $f_c)"
    new_name="${new_name#*=}"
    Begin="$(sed "${n_Begin}q;d" <<< "$applmenu")"
    newBegin="$pre<!-- $new_name -->"
    applmenu="${applmenu/$Begin/$newBegin}"
    Name="$(sed "${n_Name}q;d" <<< "$applmenu")"
    newName="$pre  <Name>$new_name</Name>"
    applmenu="${applmenu/$Name/$newName}"
    newEnd="$pre</Menu> <!-- End $new_name -->"
    applmenu="${applmenu/$End/$newEnd}"
    new_ctg="$ctg"
fi
infix="$pre<!-- $new_name -->
$pre<Menu>
$pre  <Name>$new_name</Name>
$pre  <Directory>$new_ctg.directory</Directory>
$pre  <Include>
$pre    <And>
$pre      <Category>$new_ctg</Category>
$pre    </And>
$pre  </Include>
$pre</Menu> <!-- End $new_name -->"
if ! $del; then
    [ "$ctg" != $"Main Category" ] && applmenu="${applmenu/$found/$found$'\n'$infix}" || applmenu="${applmenu/$found/$infix$'\n'$'\n'$found}"
else
    applmenu="${applmenu/$infix$'\n'/}"
    applmenu="${applmenu//$'\n\n\n'/$'\n\n'}"
fi
echo "$applmenu" > $f_menu

if ! $del; then
    [ "$LANGUAGE" != "en" ] && name_loc="Name[$LANGUAGE]=$new_name_loc"$'\n' || name_loc=""
    [ "$LANGUAGE" != "en" ] && comment_loc="Comment[$LANGUAGE]=$new_comment_loc"$'\n' || comment_loc=""
    deskdir="[Desktop Entry]
Name="$new_name"
"$name_loc"Comment="$new_comment"
"$comment_loc"Icon="$new_icon"
NoDisplay=false
Type=Directory"
    apps=$(ls -1 $casa/.local/share/applications | grep '\.desktop')$'\n'
    apps+=$(ls -1 /usr/share/applications | grep '\.desktop')
    apps=$(echo "$apps" | sort -fu)
else
    apps=$(grep -lE "Categories=.*$ctg;?" $casa/.local/share/applications/*)$'\n'
    apps+=$(grep -lE "Categories=.*$ctg;?" /usr/share/applications/*)
    apps="$(echo "$apps" | sed 's|^.*/||g')"
    apps=$(echo "$apps" | sort -fu)
    h=$(echo "$apps" | wc -l); h=$(((h+7)*20))
    unset appmenu_loc[0]
    found="$(ls $casa/.local/share/desktop-directories/$ctg.directory 2> /dev/null)"
    [ -z "$found" ] && found="/usr/share/desktop-directories/$ctg.directory"
    [ "$LANGUAGE" = "en" ] && ctg_loc="$(grep "Name=" $found)" || ctg_loc="$(grep "Name\[$LANGUAGE" $found)"
    [ -z "$ctg_loc" ] && ctg_loc="$(grep "Name=" $found)"
    ctg_loc="$(cut -d"=" -f2 <<< $ctg_loc)"
    appmenu_loc=($(echo "${appmenu_loc[*]}" | sed /\ $ctg_loc$/d))
fi

if ! $del; then
    title=$"Set new category"
    text=$"Set new category $new_ctg in:"
else
    title=$"Category $ctg invalid in:"
    msgid="\$apps

Category \$ctg change to:"
    text="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"
fi
cancel=$"Cancel"
! $del && selected_apps=`yad --center --title="$title" --window-icon=format-indent-less-rtl --width=350 --height=700 --borders=20 --text="$text" --list --multiple --no-headers --column="Desktop Files" --search-column=1 --regex-search $apps --button="$cancel":1 --button="Info":"$0 info $(basename $0)" --button="OK":0` || new_ctg_loc=`yad --center --title="$title" --window-icon=format-indent-less-rtl --width=400 --height=$h --borders=20 --text="$text" --list --editable --no-headers --column="Categories" ${appmenu_loc[@]} --entry --button="$cancel":1 --button="Info":"$0 info" --button="OK":0`
exit_code=$?

if [ $exit_code -eq 0 ]; then
    if ! $del; then
	sel_apps=(${selected_apps//|/})
	echo "$deskdir" > "/usr/share/desktop-directories/$new_ctg.directory"
	for u in $(ls /home); do
	    for s in ${sel_apps[@]}; do
		[ ! -f "/home/$u/.local/share/applications/$s" ] && cp /usr/share/applications/$s /home/$u/.local/share/applications/$s && chown $u:$u /home/$u/.local/share/applications/$s
#		[ "$ctg" = $"Main Category" ] && ctg="" && new_ctg="$new_ctg;" && sed -i -E "s/(Categories=).*/\1$new_ctg/g" /home/$u/.local/share/applications/$s || sed -i -E "s/(Categories=.*)$ctg/\1$new_ctg/g" /home/$u/.local/share/applications/$s
		[ "$ctg" = $"Main Category" ] && ctg="" && new_ctg="$new_ctg;"
		sed -i -E "s/(Categories=).*/\1$new_ctg/g" /home/$u/.local/share/applications/$s
	    done
	done
    else
	new_ctg_loc="$(echo "$new_ctg_loc" | sed 's/^ *//g')"
	new_ctg="$(grep -l "$new_ctg_loc" $casa/.local/share/desktop-directories/*.directory)"
	[ -z "$new_ctg" ] && new_ctg="$(grep -l "$new_ctg_loc" /usr/share/desktop-directories/*.directory)"
	new_ctg="$(basename "$new_ctg" | cut -d"." -f1)"
	[ -f "/usr/share/desktop-directories/$ctg.directory" ] && rm "/usr/share/desktop-directories/$ctg.directory"
	for a in $apps; do [ -f "/usr/share/applications/$a" ] && sed -i -E "s/(Categories=.*)$ctg/\1$new_ctg/g" /usr/share/applications/$a; done
	for u in $(ls /home); do
	    [ -f "/home/$u/.local/share/desktop-directories/$ctg.directory" ] && rm "/home/$u/.local/share/desktop-directories/$ctg.directory"
	    for a in $apps; do
		[ -f "/home/$u/.local/share/applications/$a" ] && sed -i -E "s/(Categories=.*)$ctg/\1$new_ctg/g" /home/$u/.local/share/applications/$a
	    done
	done
    fi
fi

title=$"Category created or deleted"
text=$"&#10;    Please wait!&#10;&#10;    Applications Menu is being adjusted ..."
ready=$"Done!"

yad --center --title="$title" --width=450 --window-icon=format-indent-less-rtl --image="info" --borders=20 --text="$text" --text-align="center" --no-buttons --close-on-unfocus &
su $user -c "appmenu-refresh; obamenu-refresh"
yad --center --title="$title" --width=400 --window-icon=format-indent-less-rtl --image="info" --borders=20 --text=$'\n'"$ready" --text-align="center" --button="OK"

exit 0
