# shellcheck shell=bash
#########################################################################
#									#
# Author: Copyright (C) 2025  Mark Grant				#
#									#
# Released under the GPLv3 only.					#
# SPDX-License-Identifier: GPL-3.0-only					#
#									#
# Purpose:								#
# Bash completion script.						#
#									#
#########################################################################


_lxcu_upgrade_proc_opts()
{
	local lxcu_dir OPTS

	lxcu_dir="/etc/lxcu"
	if [[ -n "$1" ]]; then
		lxcu_dir+="/$1"
	fi
	if [[ ! -d $lxcu_dir ]]; then
		return 0
	fi
	OPTS=$(find "$lxcu_dir" -mindepth 1 -maxdepth 1 -type d -print0 \
		2>/dev/null \
		| xargs -0 basename -a \
		| sed -e '/^apt$/d' -e '/^dosab$/d') || return
	# shellcheck disable=SC2207  # This is _the_ bash completion pattern,
	# so leave it be.
	COMPREPLY=($(compgen -W "${OPTS[*]}" -- "$2"))
}


_lxcu_upgrade()
{
	local cur prev OPTS
	local i dist rel

	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD-1]}"
	case $prev in
	-d|--dist)
		_lxcu_upgrade_proc_opts "" "$cur"
		return 0
		;;
	-r|--rel)
		for ((i = $(( COMP_CWORD - 1 )) ; i >= 0 ; i--)); do
			if [[ ${COMP_WORDS[i]} == "--dist" \
				|| ${COMP_WORDS[i]} == "-d" ]]; then
				dist="${COMP_WORDS[i+1]}"
				_lxcu_upgrade_proc_opts "$dist" "$cur"
				return 0
			fi
		done
		return 0
		;;
	-t|--type)
		for ((i = $(( COMP_CWORD - 1 )) ; i >= 0 ; i--)); do
			if [[ ${COMP_WORDS[i]} == "--dist" \
				|| ${COMP_WORDS[i]} == "-d" ]]; then
				dist="${COMP_WORDS[i+1]}"
			fi
			if [[ ${COMP_WORDS[i]} == "--rel" \
				|| ${COMP_WORDS[i]} == "-r" ]]; then
				rel="${COMP_WORDS[i+1]}"
			fi
			if [[ -n "$dist" && -n "$rel" ]]; then
				_lxcu_upgrade_proc_opts "$dist/$rel" "$cur"
				return 0
			fi
		done
		return 0
		;;
	esac
	OPTS="-d -h -r -t -V"
	OPTS+=" --dist --help --rel --type --version"
	OPTS+=" $(lxc-ls --stopped)"
	# shellcheck disable=SC2207  # This is _the_ bash completion pattern,
	# so leave it be.
	COMPREPLY=( $(compgen -W "${OPTS[*]}" -- "$cur") )
	return 0
}
complete -F _lxcu_upgrade lxcu-upgrade

