# -*- shell-script -*-
# If you have bash completion installed and want genlop to auto-complete
# packages, save this file as /etc/bash_completion.d/genlop
#
# Copyright 1999-2002 Gentoo Technologies, Inc.
# Distributed under the terms of the GNU General Public License, v2 or later
#
# Author: Geert Bevin  <gbevin@theleaf.be>
# Author: Zach Forrest <zach@disinformation.ca>
#
# Adapted for genlop by Giorgio Mandolfo <giorgio@pollycoke.org>
#
_genlop()
{
	local cur grepcmd sedcmd systemactions setsma setbig portagedir origdir args

	origdir="${PWD}"
	COMPREPLY=()
	portagedir="$(portageq envvar PORTDIR 2>/dev/null)"
	if [[ -z "${portagedir}" ]]; then
	    portagedir="/var/db/repos/gentoo"
	fi
	cur="${COMP_WORDS[COMP_CWORD]}"

	builtin cd "${portagedir}"
	grepcmd="grep -E ^${cur}.*"
	sedcmd="sed -e /^[^-]*$/d"
	case "${cur}" in
		-*)
			args='-c -e -f -h -i -g -l -n -p -r -s -S -t -u -v'
			args="${args} --current --date --file --gmt --help \
				--info --list --nocolor --pretend --rsync \
				--search --time --unmerge --version"
			COMPREPLY=( $( compgen -W "${args}" -- ${cur} ) )
			;;
		*)
			if [[ "${cur}" ]]; then
				if [[ $(echo "${cur}" | grep '/') ]]; then
					setbig=$(compgen -G "${cur}*" | ${sedcmd})"${systemactions}"
					COMPREPLY=($(echo "${setbig}" | ${grepcmd}))
				else
					setsma=$(compgen -S '/' -G "${cur}*" | ${sedcmd})"${systemactions}"
					if [[ $(echo "${setsma}" | ${grepcmd} | grep '/' | wc -l) == 1 ]]; then
						setbig=$(compgen -G "*/*" | ${sedcmd})"${systemactions}"
						COMPREPLY=($(echo "${setbig}" | ${grepcmd}))
					else
						COMPREPLY=($(echo "${setsma}" | ${grepcmd}))
					fi
				fi
			else
				setsma=$(compgen -S '/' -G "${cur}*" | ${sedcmd})"${systemactions}"
				COMPREPLY=($(echo "${setsma}"))
			fi
			;;
	esac

	builtin cd "${origdir}"
	return 0
}
complete -o default -F _genlop genlop
