#!/bin/sh

alterator_api_version=1
. alterator-sh-functions

license_dir="/usr/share/distro-licenses"
editions_dir="/usr/share/alterator/editions"

legacy_dirs="/usr/share/alt-notes 
             /usr/share/alt-license 
             /var/lib/install3/licenses"

get_edition_license()
{
	local edition_id="$(. /etc/os-release; echo $VARIANT_ID)"
	local edition_entry="$editions_dir/$edition_id/$edition_id.edition"

	if [ -n "$edition_id" ]; then
		if test -f "$edition_entry"; then
			alterator-entry get "$edition_entry" license
		fi
	fi
}

update_license_dir() {
	local distro_license_name="$(. /etc/os-release; echo $NAME | tr ' ' _)_License"
	local distro_license_version="$(. /etc/os-release; echo $VERSION_ID)"

	local distro_license="$distro_license_name/$distro_license_version"
	local edition_license="$(get_edition_license)"

	if [ -n "$edition_license" ]; then
		distro_license="$edition_license"
	fi

	test -d "$license_dir/$distro_license" || return
	dirs="$license_dir/$distro_license"
}

on_message() {
	case "$in_action" in
        	read)
			local name="${in_name:-license}"
			local license_file= path lang languages
			local dirs="$legacy_dirs"

			languages="$(printf '%s' "$in_language" |tr ';' ' ') all"
			[ "$name" != "license" ] || update_license_dir

			for path in $dirs; do
			    for lang in $languages; do
			    	    case "$lang" in
				    	    POSIX|C|all) lang="all";;
					    *) lang="$(printf %s "${lang%%_*}" |tr '[A-Z]' '[a-z]')";;
				    esac

		    		html_file="$path/$name.$lang.html"
				[ ! -s "$html_file" ] || break 2
			    done
			done

			if [ -s "$html_file" ]; then
				write_string_param "url" "$html_file"
			else
				write_error "`_ "File not found"` $name"
			fi
                        ;;
        esac
}

message_loop
