#!/bin/sh

alterator_api_version=1
profile_dir="/var/lib/install3/"
groups_dir="$profile_dir/groups"
lists_dir="$profile_dir/lists"
profiles_dir="$profile_dir/profiles"

. alterator-sh-functions

print_notfound()
{
    if [ "$1" = "notfound" ];then
	echo ""
    else
	echo "$1"
    fi
}

# Print group list
print_groups()
{
    local IFS='	'
    while read name required lists conflicts label parent depends; do
	name="${name##*/}"
	name="${name%%.directory}"
	write_table_item \
	     name "$name" \
	     parent "$parent" \
	     label "$label" \
	     required "$required" \
	     depends "$depends" \
	     lists "$(print_notfound "$lists")" \
	     conflicts "$(print_notfound "$conflicts")"
    done
}

# Raw group list
list_groups()
{
    [ ! -d "$groups_dir" ] ||
	find "$groups_dir" -type f -name "*.directory"| LC_ALL=POSIX sort |
	    xargs alterator-dump-desktop \
		-v lang="$in_language" \
		-v out="Filename;X-Alterator-Required;X-Alterator-PackageList;X-Alterator-Conflicts;Name;X-Alterator-Parent;X-Alterator-Depends" \
		-v def="notfound;no;notfound;notfound;;;" |
	    print_groups
}

# Print profile list
print_profiles()
{
    local IFS='	'
    while read name label groups; do
        name="${name##*/}"
        name="${name%%.directory}"
        write_table_item \
             name "$name" \
             label "$label" \
             groups "$groups"
    done
}

# Raw profile list
list_profiles()
{
    [ ! -d "$profiles_dir" ] ||
        find "$profiles_dir" -type f -name "*.directory"| LC_ALL=POSIX sort |
            xargs alterator-dump-desktop \
                -v lang="$in_language" \
                -v out="Filename;Name;X-Alterator-Groups" \
                -v def="notfound;;notfound" |
            print_profiles
}

# Return group content
read_group_content()
{
    gfile="$groups_dir/$1.directory"

    [ -e "$gfile" ] || return 0

    comment="$(alterator-dump-desktop -v lang="$in_language" -v out="Comment" -v def="" "$gfile")"
    pkg_list="$(alterator-dump-desktop -v lang="$in_language" -v out="X-Alterator-PackageList" -v def="" "$gfile")"

    if [ -n "$comment" ] ; then
	# Show comment if it exists
	write_string_param content "$comment"
    else
        # Show package list without comments and empty lines
        write_string_param content "$(cat "$lists_dir/$pkg_list" | grep '^[[:alnum:]]')"
    fi

}

on_message()
{
	case "$in_action" in
	    list)
		case "${in_objects}" in
                    profiles)
                        list_profiles
                        ;;
                    *)
                        list_groups
                        ;;
                esac
                ;;
	    read)
		[ -z "$in_group" ] || read_group_content "$in_group" 
	esac
}

message_loop
