# bash completion for claudia
#
# Installed by the Debian package as /usr/share/bash-completion/completions/claudia.
# Otherwise enable it with:  eval "$(claudia completion bash)"
# or save it:  claudia completion bash > ~/.local/share/bash-completion/completions/claudia

_claudia_instances() {
	claudia list --names 2>/dev/null
}

# Basenames of the remembered inputs of instance $1, for --remove-ro.
_claudia_inputs() {
	claudia show "$1" 2>/dev/null | sed -n 's|^input: .* -> /work/input/\(.*\) (ro)$|\1|p'
}

_claudia() {
	local cur prev words cword
	_init_completion || return

	local commands="build run list show rm completion"
	local cmd="" name="" i
	for ((i = 1; i < cword; i++)); do
		case "${words[i]}" in
		-*) ;;
		*)
			if [[ -z $cmd ]]; then
				cmd=${words[i]}
			elif [[ -z $name ]]; then
				name=${words[i]}
			fi
			;;
		esac
	done

	if [[ -z $cmd ]]; then
		mapfile -t COMPREPLY < <(compgen -W "$commands --version --help" -- "$cur")
		return
	fi

	case $cmd in
	run)
		case $prev in
		-r | --ro | -o | --output)
			_filedir -d
			return
			;;
		--remove-ro)
			mapfile -t COMPREPLY < <(compgen -W "$(_claudia_inputs "$name")" -- "$cur")
			return
			;;
		--allow-domain | -p | --prompt)
			return
			;;
		esac
		if [[ $cur == -* ]]; then
			mapfile -t COMPREPLY < <(compgen -W "-r --ro --remove-ro --clear-ro -o --output
				--restricted --no-restricted --allow-domain --nested --no-nested
				-p --prompt --dry-run --help" -- "$cur")
		elif [[ -z $name ]]; then
			mapfile -t COMPREPLY < <(compgen -W "$(_claudia_instances)" -- "$cur")
		fi
		;;
	show | rm)
		if [[ $cur == -* ]]; then
			local opts="--help"
			[[ $cmd == rm ]] && opts="-y --yes --help"
			mapfile -t COMPREPLY < <(compgen -W "$opts" -- "$cur")
		elif [[ -z $name ]]; then
			mapfile -t COMPREPLY < <(compgen -W "$(_claudia_instances)" -- "$cur")
		fi
		;;
	list)
		mapfile -t COMPREPLY < <(compgen -W "--names --help" -- "$cur")
		;;
	completion)
		[[ -z $name ]] && mapfile -t COMPREPLY < <(compgen -W "bash" -- "$cur")
		;;
	esac
} &&
	complete -F _claudia claudia
