# shellcheck disable=all

_generate_from_help() {
	command=$1
	# if command does not exist, try with `distrobox subcommand`
	if ! $command --help >/dev/null 2>/dev/null ; then
		command="$(echo $command | tr '-' ' ')"
	fi

	local list cur prev totalopts opts diropts

	COMPREPLY=()

	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD - 1]}"
	opts="$($command --help 2>/dev/null | sed 's|^\t||g' | grep '^--' | cut -d':' -f1 | tr '/' ' ' | tr '\n' ' ')"
	totalopts="$(echo $opts | tr ' ' '|')"
	diropts="-H|--home|--volume"
	fileopts="--file"

	if [[ ${prev} =~ ${diropts} ]]; then
		mapfile -t COMPREPLY < <(
			IFS=$'\n'
			realpath $(compgen -d -- ${cur}) 2>/dev/null
		)
		compopt -o filenames
		return 0
	fi

	if [[ ${prev} =~ ${fileopts} ]]; then
		COMPREPLY=($(compgen -f -- ${cur}))
		compopt -o filenames
		return 0
	fi
	if [[ ${prev} == "assemble" ]]; then
		COMPREPLY+=($(compgen -W "create rm" -- ${cur}))
		return 0
	fi

	if [[ ${prev} == "--image" ]] || [[ ${prev} == "-i" ]]; then
		COMPREPLY+=($(compgen -W "$(distrobox-create --compatibility)" -- ${cur}))
		return 0
	fi

	if [[ ${cur} == -* ]]; then
		COMPREPLY+=($(compgen -W "${opts}" -- ${cur}))
		return 0
	elif [[ ${command} != *"create"* ]] && [[ ${command} != *"ephemeral"* ]] &&
		[[ ${command} != *"list"* ]] && [[ ${command} != *"assemble"* ]] &&
		[[ ${command} != *"version"* ]] && [[ ${command} != *"help"* ]]; then
		while IFS= read -r line; do
			list+="$line "
		done < <(distrobox-list --no-color | tail -n+2 | cut -d'|' -f2)
		COMPREPLY=($(compgen -W "${list}" "${cur}"))
		return 0
	fi
}

__distrobox() {
	if [ "${#COMP_WORDS[@]}" == "2" ]; then
		VALID_WORDS=$(distrobox | tail -n+4 | tr -d '|' | xargs echo)
		VALID_WORDS+=" --version --help"
		COMPREPLY=($(compgen -W "${VALID_WORDS}" -- "${COMP_WORDS[1]}"))
	elif [ "${#COMP_WORDS[@]}" -gt "2" ]; then
		_generate_from_help distrobox-"${COMP_WORDS[1]}"
	fi
}

complete -F __distrobox distrobox
