# Bash completion for pkgos

_pkgos() {
	local cur prev value_flag="" suites="" i
	cur=${COMP_WORDS[COMP_CWORD]}
	prev=${COMP_WORDS[COMP_CWORD-1]}
	case ${prev} in
		-a|--arch)
			value_flag=arch
			;;
		-s|--suite)
			value_flag=suite
			;;
		-f|--format)
			COMPREPLY=( $(compgen -W "table csv json yaml value html" -- "${cur}") )
			return
			;;
		-c|--column|--sort-column)
			COMPREPLY=( $(compgen -W "Package Version Suite Arch" -- "${cur}") )
			return
			;;
		--quote)
			COMPREPLY=( $(compgen -W "all minimal none nonnumeric" -- "${cur}") )
			return
			;;
		-u|--osbpo-url)
			# A URL: no completion.
			return
			;;
	esac
	# When a comma separated list is being typed, the option it belongs
	# to is somewhere before its partially typed last value.
	if [ -z "${value_flag}" ] && [[ ${cur} == *,* ]] ; then
		for (( i = COMP_CWORD - 1 ; i >= 2 ; i-- )) ; do
			case ${COMP_WORDS[i]} in
				-a|--arch)
					value_flag=arch
					break
					;;
				-s|--suite)
					value_flag=suite
					break
					;;
			esac
		done
		if [ -z "${value_flag}" ] ; then
			return
		fi
	fi
	if [ "${value_flag}" = "arch" ] ; then
		# Only complete the last element of the comma separated list.
		COMPREPLY=( $(compgen -W "source amd64 all" -- "${cur##*,}") )
	elif [ "${value_flag}" = "suite" ] ; then
		# The -s regular expressions match anywhere in the suite names,
		# so completing the release names of the order files is good
		# enough.
		if [ -r /etc/pkgos/openstack-release.txt ] ; then
			suites="${suites} $(cat /etc/pkgos/openstack-release.txt)"
		fi
		if [ -r /etc/pkgos/debian-release.txt ] ; then
			suites="${suites} $(cat /etc/pkgos/debian-release.txt)"
		fi
		# Only complete the last element of the comma separated list.
		COMPREPLY=( $(compgen -W "${suites}" -- "${cur##*,}") )
	else
		if [ "${COMP_CWORD}" -eq 1 ] ; then
			if [[ ${cur} == -* ]] ; then
				COMPREPLY=( $(compgen -W "--version --help --debug --verbose" -- "${cur}") )
			else
				COMPREPLY=( $(compgen -W "rmadison" -- "${cur}") )
			fi
			return
		fi
		if [[ ${cur} == -* ]] ; then
			COMPREPLY=( $(compgen -W "-a --arch -r --regex -s --suite -u --osbpo-url -f --format -c --column --sort-column --sort-ascending --sort-descending --quote --noindent --max-width --fit-width --print-empty --help" -- "${cur}") )
			return
		fi
		# The Debian package names, as listed in /etc/pkgos/all-git
		if [ -r /etc/pkgos/all-git ] ; then
			COMPREPLY=( $(compgen -W "$(cat /etc/pkgos/all-git | cut -d, -f1 | cut -d/ -f3 | sed 's/\.git$//')" -- "${cur}") )
		fi
		return
	fi
	# Prefix back the elements typed before the last comma of the list.
	if [[ ${cur} == *,* ]] ; then
		COMPREPLY=( ${COMPREPLY[@]/#/${cur%,},} )
	fi
}

complete -F _pkgos pkgos
