#!/bin/sh
# shellcheck disable=SC2059

# We don't depend on gettext-bin, so provide a LANG=C-equivalent shim
# see #728612
command -v gettext > /dev/null || alias gettext='printf %s'

# EASIEST editor's basename
EASIEST="nano"

# Ensure that $HOME/.selected_editor is writeable
true >> ~/.selected_editor || exit 1


# The query output is shaped like
#   Name: editor
#   Link: /usr/bin/editor
#   Slaves:
#    editor.1.gz /usr/share/man/man1/editor.1.gz
#   Status: manual
#   Best: /usr/bin/vim.nox
#   Value: /usr/bin/vim.nox
#
#   Alternative: /bin/ed
#   Priority: -100
#   Slaves:
#    editor.1.gz /usr/share/man/man1/ed.1.gz
#
#   Alternative: /usr/bin/vim.nox
#   Priority: 40
#   Slaves:
#    editor.1.gz /usr/share/man/man1/vim.1.gz
# we care about getting {Alternative}s sorted by {Priority}, in this case
#   /usr/bin/vim.nox
#   /bin/ed
sorted_list_of_editors="$(
	alternative=
	priority=
	update-alternatives --query editor | while read -r field value; do
		case "$field" in
			'Alternative:') alternative="$value" ;;
			'Priority:')    priority="$value"    ;;
		esac
		if [ -n "$alternative" ] && [ -n "$priority" ]; then
			printf '%s\t%s\n' "$priority" "$alternative"
			alternative=
			priority=
		fi
	done | sort -n -r | cut -f 2-
)"
IFS='
'

editor_count="$(update-alternatives --list editor | wc -l)"
if [ "$editor_count" -gt 1 ]; then
	TEXTDOMAIN=sensible-utils gettext 'Select an editor.  To change later, run select-editor again.
'
	# shellcheck source=/dev/null
	[ -r ~/.selected_editor ] && . ~/.selected_editor  # Highlight the current selection with a *

	easiest=1 # If EASIEST not found, default to the best alternative
	default=
	i=0
	for e in $sorted_list_of_editors; do
		i=$(( i + 1 ))
		[ "$e" = "$SELECTED_EDITOR" ] && { ind='*'; default=$i; } || ind=' '
		if [ "${e##*/}" = "$EASIEST" ]; then
			# %c=* for the currently-selected entry, space for others
			printf "$(TEXTDOMAIN=sensible-utils gettext '%c %*u. %s        <---- easiest\n')" "$ind" "${#editor_count}" $i "$e"
			easiest=$i
		else
			printf "$(TEXTDOMAIN=sensible-utils gettext '%c %*u. %s\n')" "$ind" "${#editor_count}" $i "$e"
		fi
	done
	echo
	default="${default:-"$easiest"}"

	selected=x
	while :; do
		if [ -z "$selected" ]; then
			selected="$default"
		elif ! { [ "$selected" -gt 0 ] && [ "$selected" -le $i ]; } 2>/dev/null; then
			printf "$(TEXTDOMAIN=sensible-utils gettext 'Choose 1-%u [%u]: ')" $i "$default"
			read -r selected
		else
			break
		fi
	done
	i=0
	for e in $sorted_list_of_editors; do
		i=$(( i + 1 ))
		if [ $i -eq "$selected" ]; then
			printf '%s\n' "# Generated by $0" "SELECTED_EDITOR=\"$e\"" > ~/.selected_editor && exit 0
		fi
	done
fi
exit 1
