#!/bin/bash -efu
### This file is covered by the GNU General Public License,
### which should be included as the file LICENSE.

. alterator-entry-sh-functions

[ $# -ne 1 ] &&
	echo "Usage: $0 <category-name>" &&
	exit 1

OLD_CATEGORIES_DIR="/usr/share/alterator/desktop-directories"
NEW_CATEGORIES_DIR="/usr/share/alterator/categories"

category="$1"

if [ -d "$NEW_CATEGORIES_DIR" ]; then
	while IFS= read -d $'\0' -r file; do
		validate_alterator_entry "$file" ||
			continue

		file_type="$(get_alterator_entry_type "$file")"
		[ "$file_type" = "Category" ] ||
			continue

		file_category="$(get_alterator_entry_name "$file")"
		[ "$category" = "$file_category" ] ||
			continue

		cat "$file"
		exit 0
	done < <(find "$NEW_CATEGORIES_DIR" -maxdepth 1 -type f -print0)
fi

get_translations() {
	[ "$#" = 3 ] ||
		return 1
	local file="$1" section="$2" var="$3"

	ini_section="$(sed -n "/\[$section\]/,/^\s*\[.*\]/p" "$file")"

	echo "$ini_section" |
		sed -n -e "s/^\s*\($var\[.*\]\)\s*=\s*\(.*\)\s*$/\1 = \2/p"
}

convert_desktop_to_alterator() {
	[ -s "$1" ] ||
		return 1
	local file="$1"

	local name="$(ini_config_get "$file" "Desktop Entry" "X-Alterator-Category")"
	local display_name="$(ini_config_get "$file" "Desktop Entry" "Name")"
	local display_name_translations="$(
		get_translations "$file" "Desktop Entry" "Name" | sed "s/^/Display/"
	)"

	local comment="$(ini_config_get "$file" "Desktop Entry" "Comment")"
	local comment_translations="$(
		get_translations "$file" "Desktop Entry" "Comment"
	)"

	local icon="$(ini_config_get "$file" "Desktop Entry" "Icon")"

	case "$name" in
	"System") local weight=1000 ;;
	"Programs") local weight=990 ;;
	"Users") local weight=980 ;;
	"Network") local weight=970 ;;
	"Remote Desktop") local weight=960 ;;
	"Firewall") local weight=970 ;;
	"Graphical interface") local weight=960 ;;
	*) local weight=500 ;;
	esac

	cat <<EOF
[Alterator Entry]
Type = Category
Name = $name
DisplayName = $display_name
$display_name_translations
Comment = $comment
$comment_translations
Icon = $icon
Weight = $weight
EOF

	return 0
}

if [ -d "$OLD_CATEGORIES_DIR" ]; then
	while IFS= read -d $'\0' -r file; do
		file_category="$(
			ini_config_get "$file" "Desktop Entry" "X-Alterator-Category"
		)"
		[ "$category" = "$file_category" ] ||
			continue

		convert_desktop_to_alterator "$file"
		exit $?
	done < <(find "$OLD_CATEGORIES_DIR" -maxdepth 1 -type f -print0)
fi
