#!/bin/sh

appdir="/usr/share/alterator/applications"
dirdir="/usr/share/alterator/desktop-directories"

. 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
}

print_sections()
{
    local IFS='	'
    while read -r weight category icon name comment; do
	printf '(category "%s" icon "%s" name "%s" comment "%s")\n' \
	    "$category" \
	    "$icon" \
	    "$name" \
	    "$comment"
    done
}

list_sections()
{
    alterator-dump-desktop \
	-v lang="$in_language" \
	-v out="X-Alterator-Weight;X-Alterator-Category;Icon;Name;Comment" \
	-v def="0;X-Alterator-System;altlinux;noname;" \
	$dirdir/*.directory |
	sort -r -g -k1,1 |
	print_sections
}

print_modules()
{
    local IFS='	'
    while read weight ui uri help category desktopfile name; do
	[ "$ui" = "all" ] || [ "$ui" = "${in_ui:-all}" ] || continue;

	desktopfile="${desktopfile##*/}"
	desktopfile="${desktopfile%%.desktop}"

	printf '(uri "%s" help "%s" category "%s" desktopfile "%s" name "%s")\n' \
	    "$uri" \
	    "$help" \
	    "$category" \
	    "$desktopfile" \
	    "$name"
    done
}

list_modules()
{
    alterator-dump-desktop \
	-v lang="$in_language" \
	-v out="X-Alterator-Weight;X-Alterator-UI;X-Alterator-URI;X-Alterator-Help;Categories;Filename;Name" \
	-v def="0;all;/notfound;notfound;X-Alterator-Other;notfound;noname" \
	$appdir/*.desktop|
	sort -r -g -k1,1|
	print_modules
}


read_module()
{
    local fname="$(print_first_readable "$ALTERATOR_DATADIR" "/applications/$in_desktopfile.desktop")"
    local IFS='	'

    [ ! -f "$fname" ] ||
    alterator-dump-desktop \
	-v lang="$in_language" \
	-v out="X-Alterator-UI;X-Alterator-URI;X-Alterator-Help;Name" \
	-v def="all;/notfound;notfound;" \
	$fname|
	(read ui uri help name;
	    [ "$ui" = "all" ] || [ "$ui" = "${in_ui:-all}" ] || return;
	    write_string_param uri "$uri"
	    write_string_param help "$help"
	    write_string_param name "$name")
}

###FIXME: alterator_api_version = 1
on_message()
{
	case "$in_action" in
	    read)
		echo '('
		read_module
		echo ')'
		;;
	    list)
		echo '('
		case "$in__objects" in
		    avail_sections) list_sections;;
		    avail_modules) list_modules;;
		esac
		echo ')'
		;;
	    *)
		echo '#f'
		;;
	esac
}

message_loop
