#!/bin/bash
# SPDX-License-Identifier: (LGPL-2.1 OR LGPL-3.0)
# Copyright (C) SUSE LLC 2019-2022, all rights reserved.

# This script autocompletes "rapido" subcommands and "rapido cut" image
# generators.
# Source it in your bashrc:
#   . <rapido_dir>/tools/bash_completion
#
# or create a bash_completion.d link:
#   ln -s <rapido_dir>/tools/bash_completion /etc/bash_completion.d/rapido

__rapido()
{
	local bin cut_dir cur rcmd max_off seen_boot
	local -a comps
	bin="$(realpath -e $1)"

	# we only want to complete the rapido script, not dirs, etc.
	[ -f "$bin" ] || return 0
	[ -x "$bin" ] || return 0

	cut_dir="${bin%/*}/cut"
	[ -d "${cut_dir}" ] || return 0

	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"

	if (( $COMP_CWORD <= 1 )); then
		comps=(boot cut help list setup-network teardown-network)
		COMPREPLY=( $(compgen -W "${comps[*]}" -- ${cur}) )
		return 0
	fi

	rcmd="${COMP_WORDS[1]}"	# rapido command should be at offset 1
	if [[ $rcmd == "cut" ]]; then
		seen_boot=0
		max_off=2
		for (( i=2; i<=$COMP_CWORD; i++ )); do
			case "${COMP_WORDS[i]}" in
			"-B")
				(( seen_boot == 0 )) || return 0
				seen_boot=1
				(( max_off++ ))
				;;
			"-f")
				if (( $i == $COMP_CWORD - 1 )); then
					# complete -f <filename>
					COMPREPLY=( $(compgen -o filenames -A file -- ${cur}) )
					return 0
				fi

				(( max_off+=2 ))
				(( i++ ))	# skip any file name
				;;
			"-x")
				# don't attempt to complete -x <cmd> string
				(( $i == $COMP_CWORD - 1 )) && return 0
				(( max_off+=2 ))
				(( i++ ))	# skip script
				;;
			esac
		done
		(( $COMP_CWORD > $max_off )) && return 0

		# complete cut scripts based on dir listing, with prefix and
		# suffix stripped, and underscores replaced with hyphens.
		comps=("$cut_dir"/*.sh)
		[[ ${comps[0]} == "$cut_dir/*.sh" ]] && return 0 # !nullglob
		comps=("${comps[@]#${cut_dir}/}")
		comps=("${comps[@]%.sh}")
		comps=("${comps[@]//_/-}")
		comps+=(-f -x)
		(( seen_boot == 0 )) && comps+=(-B)
		COMPREPLY=( $(compgen -W "${comps[*]}" -- ${cur}) )
	fi
	return 0
}

complete -F __rapido rapido
complete -F __rapido ./rapido
