#!/bin/sh
appdir="/usr/share/alterator/applications"
dirdir="/usr/share/alterator/desktop-directories"
datadir="/usr/share/alterator-menu/"

. alterator-sh-functions

# <path1>:<path2> <file> -> <readable path><file>
print_first_readable(){
  local IFS=":"
  for d in $1; do
    if [ -f "$d$2" ]; then
      echo -n "$d$2"
      return
    fi
  done
}


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)
		local fname="$(print_first_readable "$ALTERATOR_DATADIR" "/applications/$in_desktopfile.desktop")"
		if [ -f "$fname" ]; then
		    local result="$(desktop_awk "" "$fname")"
		    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
