#!/bin/sh

alt_datadir="/usr/share/alterator/"
appdir="$alt_datadir/applications"
dirdir="$alt_datadir/desktop-directories"
datadir="/usr/share/alterator-menu/"

. alterator-sh-functions

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

directory_awk()
{
    awk -f "$datadir/directory.awk" \
	-v lang="$in_language" \
	"$@"
}

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

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

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

list_directories()
{
    directory_awk $dirdir/*.directory|
	sort -r -g -k1,1 |
	print_directory
}


list_entries()
{
    desktop_awk "$1" $appdir/*.desktop|
        sort -r -g -k1,1|
        print_entry
}

on_message()
{
	case "$in_action" in
	    read)
		if [ -f "$appdir/$in_desktopfile.desktop" ];then
		    local result="$(desktop_awk "" "$appdir/$in_desktopfile.desktop")"
		    if [ -n "$result" ];then
			echo "$result" | print_one_entry
		    else
			write_nop
		    fi
		else
		    write_nop
		fi
		;;
	    list)
		echo '('
		if [ "$in__objects" = "/" ];then
		    list_directories
		else
		    list_entries "$in__objects"
		fi
		echo ')'
		;;
	    *)
		echo '#f'
		;;
	esac
}

message_loop
