#!/bin/sh

alias cp=cp

APPS_DIR=/var/cache/applications
NEW_APPS_DIR=/var/lib/menu/tmp_xdg_menu
if [ "$UID" != 0 ]
then
    APPS_DIR=~/.local/share/applications
    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 "$uf" "$NEW_APPS_DIR"
done

# save user edited menus
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
	    cp -f $f $NEW_APPS_DIR
	    continue
	fi
    fi
    # remove uninstalled menus
    [ -e $NEW_APPS_DIR/$f ] || rm -f $APPS_DIR/$f
done

popd >/dev/null 2>&1

# move new menus
mv -f $NEW_APPS_DIR/* $APPS_DIR 2>/dev/null
rm -rf $NEW_APPS_DIR
