#!/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- -f1)
echo "active wm: $wm "
if [[ "$wm" == "zzz" ]]; then
	# IceWM window manager has personal menu in IceWM menu format at ~/.icewm/personal
	desktop_file=$1
	cp "$desktop_file"  /"$XDG_DESKTOP_DIR"/ 
fi

if [[ "$wm" == "rox" ]]; then
	desktop_file=$1
	set -x
### echo "starting set-grid.sh: parm1: $1  parm2: $2" > test.txt

LINES_TO_ADD=$(mktemp)
export LINES_TO_ADD

disp=${DISPLAY#:}
disp=${disp%.[0-9]}
wm=$(cat $HOME/.desktop-session/desktop-code.$disp | cut -d- -f2)
PINBOARD="$HOME/.config/rox.sourceforge.net/ROX-Filer/pb_antiX-$wm"
echo "at start wm: $wm    PINBOARD: $PINBOARD"
ICON_SIZE=$(grep "display_large_width" "$HOME/.config/rox.sourceforge.net/ROX-Filer/Options")
ICON_SIZE=${ICON_SIZE#*>}
ICON_SIZE=${ICON_SIZE%<*}
SCREEN_RES=$(xdpyinfo  | grep -oP 'dimensions:\s+\K\S+')
ICON_OFFSET=$(($ICON_SIZE / 2))
SCREEN_ROWS=$((${SCREEN_RES#*x} / $ICON_SIZE))
SCREEN_COLUMNS=$((${SCREEN_RES%x*} / $ICON_SIZE))
AVAILABLE_CORDS=()

#function to build an array of the available grid cordinates based on screen size
function make_grid_array() {
    cord1="$ICON_OFFSET"
    for gridc in  `seq 1 $SCREEN_COLUMNS`; do
        cord2=$ICON_OFFSET
        for gridc in  `seq 1 $SCREEN_ROWS`; do
            AVAILABLE_CORDS+=("$cord1|$cord2")
            cord2=$(($cord2 + $ICON_SIZE))
        done
        cord1=$(($cord1 + $ICON_SIZE))
    done
}

#Function to remove the currently used icon locations from the available cords array of locations.
function get_current_locations() {
    #echo "get_current locations: $PINBOARD"
    local IFS=$'\n'
    count=0
    for line in $(grep "<icon.*" $PINBOARD |sed "s/\ \ //ig" |tr -d "\""); do
        x=$(echo $line |cut -d " " -f2) && x=${x#*=}
        y=$(echo $line |cut -d " " -f3) && y=${y#*=}
        xstart=$(($x - $ICON_OFFSET))
        xend=$(($x + $ICON_OFFSET))
        xarray=($(seq $xstart $xend))
        ystart=$(($y - $ICON_OFFSET))
        yend=$(($y + $ICON_OFFSET))
        yarray=($(seq $ystart $yend))

        for cordset in "${AVAILABLE_CORDS[@]}"; do
            cordsetx=${cordset%|*}
            cordsety=${cordset#*|}
            if [[ " ${xarray[@]} " =~  "${cordsetx}" ]] && [[ " ${yarray[@]} " =~ "${cordsety}" ]]; then
                unset "AVAILABLE_CORDS[$count]"
                count=$((count+1));
                break;
            fi
            count=$((count+1));
        done
    done
}

function set_new_items() {
    #echo "set_new_items: ${AVAILABLE_CORDS[@]}"
    for item in $(find ${XDG_DESKTOP_DIR:-$HOME/Desktop} -wholename "*.desktop"); do
        name=$(grep "^Name=" $item)
        name=${name#*=}
        name=$(echo "$name" | head -n 1)
        echo "$name"
        for i in "${!AVAILABLE_CORDS[@]}"; do
            cordset="${AVAILABLE_CORDS[$i]}"
            cordsetx=${cordset%|*}
            cordsety=${cordset#*|}
            echo "<icon x='$cordsetx' y='$cordsety' label='$name'>$item</icon>" >> $LINES_TO_ADD
            unset "AVAILABLE_CORDS[$i]"
            break;
        done
    done
}

function set_new_item1() {
    # parm1=path/filename of .desktop file, parm2=localized name
    item=$1  
    if [ -s "$2" ]; then
        name=$2
    else
        name=$(grep "^Name=" "$item")
        name=$(echo "$name" | head -n 1)
        name=${name#*=}
    fi
    echo "$name"
    echo "avail cords: ${AVAILABLE_CORDS[@]}"
    for i in "${!AVAILABLE_CORDS[@]}"; do
        cordset="${AVAILABLE_CORDS[$i]}"
        cordsetx=${cordset%|*}
        cordsety=${cordset#*|}
        ###Next line fixed by PPC - using " instead of ' (so inside quotes he use \" )
        echo "  <icon x=\"$cordsetx\" y=\"$cordsety\" label=\"$name\">$item</icon>" >> $LINES_TO_ADD
        unset "AVAILABLE_CORDS[$i]"
        break;
    done
}

### Mainline code
make_grid_array
get_current_locations
if [ -z "$1" ]; then
    # no desktop entry passed, process all ~/Desktop files
    set_new_items
else
    # desktop entry passed, just add it to pinboard
    set_new_item1 "$1" "$2"
fi
### Add lines to active pinboard
if [ -s "$LINES_TO_ADD" ]; then
    echo "Current pinboard: \n$(cat ${PINBOARD})"
    echo "Adding lines: $(cat ${LINES_TO_ADD})"
    LINE_NUMBER_MATCHING=$(sed -n '/^<\/pinboard>*/=' $PINBOARD) && sed -i "$((${LINE_NUMBER_MATCHING} - 1))r $LINES_TO_ADD" $PINBOARD
    echo "Revised pinboard: \n$(cat ${PINBOARD})"
fi
### Remove temporary files
rm -f -- "$LINES_TO_ADD"
desktop-session-exit -R
fi
