#!/bin/sh

APPS_DIR=/usr/share/applications-alt
NEW_APPS_DIR=/var/lib/menu/tmp_xdg_menu
if [ "$UID" != 0 ]
then
    APPS_DIR=~/.local/share/applications-alt
    NEW_APPS_DIR=~/.local/share/tmp_xdg_menu
fi

mkdir -p $APPS_DIR $NEW_APPS_DIR >/dev/null 2>&1

pushd $APPS_DIR >/dev/null 2>&1

# save user created menus
ls -1 -I 'alt-*.desktop' -I 'gnome-*.desktop' -I 'kde-*.desktop' 2>/dev/null | \
while read uf
do
    cp -f --reply=yes "$uf" "$NEW_APPS_DIR"
done

# save user edited menus
I=0
for f in `ls -1 alt-*.desktop gnome-*.desktop kde-*.desktop 2>/dev/null`
do
    if [ "$UID" != 0 ]
    then
	if grep -q X-ALT-UserEdited=true $f
	then
	    `which cp` -f $f $NEW_APPS_DIR
	    continue
	fi
    fi
    # remove uninstalled menus
    [ -e $NEW_APPS_DIR/$f ] || rm -f $APPS_DIR/$f
    ((I++))
done

popd >/dev/null 2>&1

# move new menus
mv -f $NEW_APPS_DIR/* $APPS_DIR

echo OK
