#!/bin/sh

XDG_DATA_DIRS="/usr/share/alterator/"
APPLICATIONS_DIR="$XDG_DATA_DIRS/applications"
DIRECTORIES_DIR="$XDG_DATA_DIRS/desktop-directories"
DATADIR="/usr/share/alterator-menu/"

desktop_awk()
{
    local category="$1";shift
    
    awk -f "$DATADIR/desktop.awk" \
	-v lang="${in_language%%;*}" \
	-v category="$category"\
	-v ui="${in_ui:-qt}"\
	$APPLICATIONS_DIR/*.desktop
}

directory_awk()
{
    awk -f "$DATADIR/directory.awk" \
	-v lang="${in_language%%;*}" \
	$DIRECTORIES_DIR/*.directory
}

print_directory()
{
    while read weight category name; do
	desktop_awk "$category"|grep -vqs '^$' &&
	    printf '("%s" label "%s")\n' "$category" "$name"
    done
}

list_directories()
{
    directory_awk|
	sort -r -g -k1,1 |
	print_directory
}

print_entry()
{
    while read weight uri name;do
	printf '("%s" label "%s")' "$uri" "$name"
    done
}

list_entries()
{
    desktop_awk "$1"|
        sort -r -g -k1,1|
        print_entry
}

_()
{
    LANG=${in_language%%;*}.utf8 gettext "alterator-standalone" "$1"
}

. /usr/share/alterator/build/backend3.sh

on_message()
{
	case "$in_action" in
	    list)
		echo '('
		if [ "$in__objects" = "/" ];then
		    list_directories
		else
		    list_entries "$in__objects"
		fi
		echo ')'
		;;
	    *)
		echo '#f'
		;;
	esac
}

message_loop
