# man.sh(1) completion
#
_man_sh()
{
	local cur prev sect manpath

	COMPREPLY=()
	cur=${COMP_WORDS[COMP_CWORD]}
	prev=${COMP_WORDS[COMP_CWORD-1]}

	_expand || return 0

	# default completion if parameter contains /
	if [[ "$cur" == */* ]]; then
		_filedir
		return 0
	fi

	manpath=$( command man.sh --path )

	if [ -z "$manpath" ]; then
		COMPREPLY=( $( compgen -c -- $cur ) )
		return 0
	fi

	# determine manual section to search
	[[ "$prev" == [0-9ln] ]] && sect=$prev || sect='*'

	manpath=$manpath:
	if [ -n "$cur" ]; then
		manpath="${manpath//://*man$sect/$cur* } ${manpath//://*cat$sect/$cur* }"
	else
		manpath="${manpath//://*man$sect/ } ${manpath//://*cat$sect/ }"
	fi
		
	# redirect stderr for when path doesn't exist
	COMPREPLY=( $( eval command ls "$manpath" 2>/dev/null ) )
	# weed out directory path names and paths to man pages
	COMPREPLY=( ${COMPREPLY[@]##*/?(:)} )
	# strip suffix from man pages
	COMPREPLY=( ${COMPREPLY[@]%.@(gz|bz2|lzma|xz|Z)} )
	COMPREPLY=( $( compgen -W '${COMPREPLY[@]%.*}' -- "${cur//\\\\/}" ) )

	[[ "$prev" != [0-9ln] ]] && _filedir '[0-9ln]'

	return 0
}
complete -F _man_sh $filenames man.sh
