#!/bin/sh

alterator_api_version=1
. alterator-sh-functions

editions_dir="/usr/share/alterator/editions"
exec="/usr/lib/alterator/backends/edition"

on_message() {
	case "$in_action" in
	list)
		find "$editions_dir" -name '*.edition' | while read -r file; do
			filename=$(basename "$file")
			edition="${filename%.*}"

			local display_name

			languages="$(printf '%s' "$in_language" | tr ';' ' ') all"
			for lang in $languages; do
				case "$lang" in
				POSIX | C | all) lang="en" ;;
				*) lang="$(printf %s "${lang%%_*}" | tr '[A-Z]' '[a-z]')" ;;
				esac
				display_name=$(alterator-entry get "${file}" "display_name.${lang}") || continue
				break
			done

			write_enum_item "${edition}" "${display_name}"
		done
		;;

	read)
		if [ -n "$in_name" ]; then
			edition="$in_name"
		else
			edition=$(${exec} get)
		fi

		write_string_param name "$edition"
		write_string_param screenshots "$editions_dir/$edition/screenshots"

		html_file="$(LC_ALL=$in_language ${exec} description $edition --path)"

		if [ -s "$html_file" ]; then
			write_string_param "description" "$html_file"
		else
			write_error "$(_ "description not found") $in_name"
		fi
		;;

	write)
		${exec} set "$in_name"
		;;
	esac
}

message_loop
