#!/bin/sh

set -e

if [ -z "${1}" ] ; then
	echo "This tool displays an interactive picker, using fzf when available"
	echo "and a numbered menu otherwise, and prints the selected item."
	echo "Usage: ${0} <prompt> <item> [<item> ...]"
	echo "Example: pkgos-choose 'What license?' 'Apache-2.0' 'Expat' 'BSD-2-clause'"
	exit 1
fi

PROMPT=${1}
shift
NB=$#

fzf_pick () {
	printf '%s\n' "$@" | fzf \
		--prompt="${PROMPT} > " \
		--reverse \
		--height=40% \
		--no-multi
}

numbered_pick () {
	i=1
	for ITEM in "$@" ; do
		echo "${i} - ${ITEM}" >&2
		i=$(( ${i} + 1 ))
	done
	echo -n "${PROMPT} Enter a number between 1 and ${NB}: " >&2
	while read -r CHOICE ; do
		case ${CHOICE} in
		''|*[!0-9]*)
			echo -n "Please enter a number between 1 and ${NB}: " >&2
			continue
			;;
		esac
		if [ "${CHOICE}" -lt 1 ] || [ "${CHOICE}" -gt "${NB}" ] ; then
			echo -n "Please enter a number between 1 and ${NB}: " >&2
			continue
		fi
		i=1
		for ITEM in "$@" ; do
			if [ "${i}" = "${CHOICE}" ] ; then
				echo "${ITEM}"
				exit 0
			fi
			i=$(( ${i} + 1 ))
		done
	done
	exit 1
}

if [ -t 0 ] && which fzf >/dev/null 2>&1 ; then
	PICKED=$(fzf_pick "$@") || exit 1
	echo "${PICKED}"
else
	numbered_pick "$@"
fi
