#!/bin/bash
# Unit tests for the pkgos bash completion: the completion script is
# sourced, then completions are simulated through COMP_WORDS,
# COMP_CWORD and COMPREPLY.

set -e

if ! type bash > /dev/null 2>&1 ; then
	echo "bash not found: skipping"
	exit 0
fi

COMPLETION_FILE=../../bash-completion/pkgos
if ! [ -r ${COMPLETION_FILE} ] ; then
	echo "${COMPLETION_FILE} not found"
	exit 1
fi
. ${COMPLETION_FILE}

complete -p pkgos > /dev/null || {
	echo "pkgos completion is not registered"
	exit 1
}

# Completing the sub command
COMP_WORDS=(pkgos "")
COMP_CWORD=1
_pkgos
if ! [[ " ${COMPREPLY[@]} " == *" rmadison "* ]] ; then
	echo "rmadison was not completed"
	exit 1
fi

# Completing the -a values
COMP_WORDS=(pkgos rmadison -a "")
COMP_CWORD=3
_pkgos
if ! [[ " ${COMPREPLY[@]} " == *" source "* ]] ; then
	echo "source was not completed for -a"
	exit 1
fi
if ! [[ " ${COMPREPLY[@]} " == *" amd64 "* ]] ; then
	echo "amd64 was not completed for -a"
	exit 1
fi

# Completing the last element of a comma separated -a list
COMP_WORDS=(pkgos rmadison -a amd64,)
COMP_CWORD=3
_pkgos
if ! [[ " ${COMPREPLY[@]} " == *" amd64,all "* ]] ; then
	echo "amd64,all was not completed"
	exit 1
fi

# Completing the flags of the rmadison command
COMP_WORDS=(pkgos rmadison -)
COMP_CWORD=2
_pkgos
if ! [[ " ${COMPREPLY[@]} " == *" --format "* ]] ; then
	echo "--format was not completed"
	exit 1
fi
if ! [[ " ${COMPREPLY[@]} " == *" --sort-column "* ]] ; then
	echo "--sort-column was not completed"
	exit 1
fi

# Completing the Debian package names from /etc/pkgos/all-git, when it
# is available (it is not part of this package's build environment).
if [ -r /etc/pkgos/all-git ] ; then
	COMP_WORDS=(pkgos rmadison "")
	COMP_CWORD=2
	_pkgos
	if [ ${#COMPREPLY[@]} -eq 0 ] ; then
		echo "no package name was completed from /etc/pkgos/all-git"
		exit 1
	fi
fi

# Completing the -s values from the release order files, when they are
# available (they are not part of this package's build environment).
if [ -r /etc/pkgos/openstack-release.txt ] ; then
	COMP_WORDS=(pkgos rmadison -s "")
	COMP_CWORD=3
	_pkgos
	if ! [[ " ${COMPREPLY[@]} " == *" hibiscus "* ]] ; then
		echo "hibiscus was not completed for -s"
		exit 1
	fi
	if ! [[ " ${COMPREPLY[@]} " == *" bookworm "* ]] ; then
		echo "bookworm was not completed for -s"
		exit 1
	fi
fi

echo "All pkgos completion tests passed."
