#!/bin/bash

IFS=$'\n'
h_file="$HOME/.config/rox.sourceforge.net/ROX-Filer/marked-directories.lst"
hist=($(cat $h_file))
mv $h_file $h_file~

g_file="$HOME/.config/rox.sourceforge.net/ROX-Filer/Groups.xml"
groups="$(cat $g_file)"
groups_pre="$groups"
xml="$groups"

while [[ "$xml" =~ "<directory>" ]]; do
    xml=${xml#*name=}
    nr=${xml:1:1}" "
    xml=${xml#*\<directory\>}
    dir=${xml%%\<\/directory\>*}
    found=false
    if [[ "${hist[@]}" =~ "$dir‖" ]]; then
	k=$(grep -n "$dir‖" <<< "${hist[*]}" | cut -d: -f1)
	if [ $k -gt 0 ]; then
	    ((k--))
	    label="${hist[$k]#*‖}"
	    [[ "$label" =~ ^[0-9]\  ]] && label="${label:2}"
	    unset "hist[$k]"
	    found=true
	fi
    else
	if [[ "${hist[@]}" =~ "‖$nr" ]]; then
	    k=$(grep -n "‖$nr" <<< "${hist[*]}" | cut -d: -f1)
	    [ $k -gt 0 ] && ((k--)) && unset "hist[$k]"
	elif [ ${#hist[@]} -gt 29 ]; then
	    unset "hist[((${#hist[@]}-1))]"
	fi
	found=true
	label=$(basename "$dir")
    fi
    if $found; then hist=("$dir‖$nr$label" ${hist[@]}); fi
    nr=""
done

hist_tmp=(${hist[@]//‖/|})
hist_sort=($(sort -ft '|' -k 2 <<< "${hist_tmp[*]}"))
hist=(${hist_sort[@]//|/‖})

for h in ${hist[@]}; do
    pfad="${h%‖*}"
    if [ -d "$pfad" ]; then echo "$h" >> $h_file; fi
done

lang_dir=$"C"
title=$"Marked Folders"
button=$"Help"

list-cmd-edit --list=$h_file --arg=$title --icon=$HOME/.icons/marked-dir.png --winicon=$HOME/.icons/marked-dir.png --deco=true --shut=false --parent="$0" --opt="--button=$button:yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#marked-dir"
button=$?

[[ $button =~ 4|252 ]] && exit $button

mv $h_file~ $h_file.bak
hist=($(cat $h_file))

groups_head="${groups%%\<groups\>*}<groups>"$'\n'
groups_tail="</groups>"
groups=""
for ((k=0; k<${#hist[@]}; k++)); do
    dir="${hist[$k]%‖*}"
    label="${hist[$k]##*‖}"
    nr_=${label:0:2}
    digit="^[0-9] $"
    nr=${label::1}
    if [[ $nr_ =~ $digit ]]; then
	groups="$groups<group name=\"$nr\"><directory>$dir</directory></group>"$'\n'
    fi
done
groups="$groups_head$groups$groups_tail"

[ "$groups" != "$groups_pre" ] && echo "$groups" > $g_file

exit 0
