# 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 | 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
		COMPREPLY=($(compgen -d -- ${cur}))
		return 0
	fi

	if [[ ${prev} =~ ${fileopts} ]]; then
		COMPREPLY=($(compgen -f -- ${cur}))
		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"* ]]; then
		while IFS= read -r line; do
			list+="$line "
		done < <(distrobox-list --no-color | tail -n+2 | awk '{print $3}')
		COMPREPLY=($(compgen -W "${list}" "${cur}"))
		return 0
	fi
}

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

complete -F __distrobox distrobox
