# -*- mode: shell-script; sh-basic-offset: 8; indent-tabs-mode: t -*-
# ex: ts=8 sw=8 noet filetype=sh
#
#   bash_completion - programmable completion functions for bash 3.x
#		      (backwards compatible with bash 2.05b)
#
#   Copyright © 2006-2008, Ian Macdonald <ian@caliban.org>
#             © 2009, Bash Completion Maintainers
#                     <bash-completion-devel@lists.alioth.debian.org>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2, or (at your option)
#   any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software Foundation,
#   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#   The latest version of this software can be obtained here:
#
#   http://bash-completion.alioth.debian.org/
#
#   RELEASE: 1.x

if [[ $- == *v* ]]; then
	BASH_COMPLETION_ORIGINAL_V_VALUE="-v"
else
	BASH_COMPLETION_ORIGINAL_V_VALUE="+v"
fi

if [[ -n $BASH_COMPLETION_DEBUG ]]; then
	set -v
else
	set +v
fi

# Alter the following to reflect the location of this file.
#
[ -n "$BASH_COMPLETION" ] || BASH_COMPLETION=/etc/bash_completion
[ -n "$BASH_COMPLETION_DIR" ] || BASH_COMPLETION_DIR=/etc/bash_completion.d
[ -n "$BASH_COMPLETION_COMPAT_DIR" ] || BASH_COMPLETION_COMPAT_DIR=/etc/bash_completion.d
readonly BASH_COMPLETION BASH_COMPLETION_DIR BASH_COMPLETION_COMPAT_DIR

# Set a couple of useful vars
#
UNAME=$( uname -s )
# strip OS type and version under Cygwin (e.g. CYGWIN_NT-5.1 => Cygwin)
UNAME=${UNAME/CYGWIN_*/Cygwin}

case ${UNAME} in
	Linux|GNU|GNU/*) USERLAND=GNU ;;
	*) USERLAND=${UNAME} ;;
esac

# features supported by bash 2.05 and higher
if [ ${BASH_VERSINFO[0]} -eq 2 ] && [[ ${BASH_VERSINFO[1]} > 04 ]] ||
   [ ${BASH_VERSINFO[0]} -gt 2 ]; then
	declare -r bash205=$BASH_VERSION 2>/dev/null || :
	default="-o default"
	dirnames="-o dirnames"
	filenames="-o filenames"
fi
# features supported by bash 2.05b and higher
if [ ${BASH_VERSINFO[0]} -eq 2 ] && [[ ${BASH_VERSINFO[1]} = "05b" ]] ||
   [ ${BASH_VERSINFO[0]} -gt 2 ]; then
	declare -r bash205b=$BASH_VERSION 2>/dev/null || :
	nospace="-o nospace"
fi
# features supported by bash 3.0 and higher
if [ ${BASH_VERSINFO[0]} -gt 2 ]; then
	declare -r bash3=$BASH_VERSION 2>/dev/null || :
	bashdefault="-o bashdefault"
	plusdirs="-o plusdirs"
fi
# features supported by bash 4.0 and higher
if [ ${BASH_VERSINFO[0]} -gt 3 ]; then
	declare -r bash4=$BASH_VERSION 2>/dev/null || :
fi

# Turn on extended globbing and programmable completion
shopt -s extglob progcomp

# A lot of the following one-liners were taken directly from the
# completion examples provided with the bash 2.04 source distribution

# Make directory commands see only directories
complete -d pushd

# The following section lists completions that are redefined later
# Do NOT break these over multiple lines.
#
# START exclude -- do NOT remove this line
complete -f -X '!*.?(t)bz?(2)' bunzip2
# TODO: see #455510
#complete -f -X '!*.?(t)bz?(2)' bzcat bzcmp bzdiff bzegrep bzfgrep bzgrep
complete -f -X '!*.*' bzcat bzcmp bzdiff bzegrep bzfgrep bzgrep
complete -f -X '!*.@(zip|ZIP|jar|JAR|exe|EXE|pk3|war|wsz|ear|zargo|xpi|sxw|ott|od[fgpst]|epub)' unzip zipinfo
complete -f -X '*.Z' compress znew
complete -f -X '!*.@(Z|gz|tgz|Gz|dz)' gunzip
# TODO: see #455510
#complete -f -X '!*.@(Z|gz|tgz|Gz|dz)' zcmp zdiff zcat zegrep zfgrep zgrep zless zmore
complete -f -X '!*.*' zcmp zdiff zcat zegrep zfgrep zgrep zless zmore
complete -f -X '!*.Z' uncompress
complete -f -X '!*.@(gif|jp?(e)g|miff|tif?(f)|pn[gm]|p[bgp]m|bmp|xpm|ico|xwd|tga|pcx|GIF|JP?(E)G|MIFF|TIF?(F)|PN[GM]|P[BGP]M|BMP|XPM|ICO|XWD|TGA|PCX)' ee
complete -f -X '!*.@(gif|jp?(e)g|tif?(f)|png|p[bgp]m|bmp|x[bp]m|rle|rgb|pcx|fits|pm|GIF|JPG|JP?(E)G|TIF?(F)|PNG|P[BGP]M|BMP|X[BP]M|RLE|RGB|PCX|FITS|PM)' xv qiv
complete -f -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF)?(.gz|.GZ|.bz2|.BZ2|.Z))' gv ggv kghostview
complete -f -X '!*.@(dvi|DVI)?(.@(gz|Z|bz2))' xdvi
complete -f -X '!*.@(dvi|DVI)?(.@(gz|Z|bz2))' kdvi
complete -f -X '!*.@(dvi|DVI)' dvips dviselect dvitype dvipdf advi dvipdfm dvipdfmx
complete -f -X '!*.@(pdf|PDF)' acroread gpdf xpdf
complete -f -X '!*.@(?(e)ps|?(E)PS|pdf|PDF)' kpdf
complete -f -X '!*.@(@(?(e)ps|?(E)PS|pdf|PDF|dvi|DVI)?(.gz|.GZ|.bz2|.BZ2)|cb[rz]|CB[RZ]|djv?(u)|DJV?(U)|dvi|DVI|gif|jp?(e)g|miff|tif?(f)|pn[gm]|p[bgp]m|bmp|xpm|ico|xwd|tga|pcx|GIF|JP?(E)G|MIFF|TIF?(F)|PN[GM]|P[BGP]M|BMP|XPM|ICO|XWD|TGA|PCX)' evince okular
complete -f -X '!*.@(?(e)ps|?(E)PS|pdf|PDF)' ps2pdf ps2pdf12 ps2pdf13 ps2pdf14 ps2pdfwr
complete -f -X '!*.texi*' makeinfo texi2html
complete -f -X '!*.@(?(la)tex|?(LA)TEX|texi|TEXI|dtx|DTX|ins|INS)' tex latex slitex jadetex pdfjadetex pdftex pdflatex texi2dvi
complete -f -X '!*.@(mp3|MP3)' mpg123 mpg321 madplay
complete -f -X '!*@(.@(mp?(e)g|MP?(E)G|wma|avi|AVI|asf|vob|VOB|bin|dat|divx|DIVX|vcd|ps|pes|fli|flv|FLV|viv|rm|ram|yuv|mov|MOV|qt|QT|wmv|mp[234]|MP[234]|m4[pv]|M4[PV]|mkv|MKV|ogg|OGG|ogm|OGM|wav|WAV|asx|ASX|mng|MNG|srt|m[eo]d|M[EO]D|s[3t]m|S[3T]M|it|IT|xm|XM)|+([0-9]).@(vdr|VDR))' xine aaxine fbxine kaffeine
complete -f -X '!*.@(avi|asf|wmv)' aviplay
complete -f -X '!*.@(rm?(j)|ra?(m)|smi?(l))' realplay
complete -f -X '!*.@(mpg|mpeg|avi|mov|qt)' xanim
complete -f -X '!*.@(ogg|OGG|m3u|flac|spx)' ogg123
complete -f -X '!*.@(mp3|MP3|ogg|OGG|pls|m3u)' gqmpeg freeamp
complete -f -X '!*.fig' xfig
complete -f -X '!*.@(mid?(i)|MID?(I)|cmf|CMF)' playmidi
complete -f -X '!*.@(mid?(i)|MID?(I)|rmi|RMI|rcp|RCP|[gr]36|[GR]36|g18|G18|mod|MOD|xm|XM|it|IT|x3m|X3M|s[3t]m|S[3T]M|kar|KAR)' timidity
complete -f -X '!*.@(m[eo]d|M[EO]D|s[3t]m|S[3T]M|xm|XM|it|IT)' modplugplay
complete -f -X '*.@(o|so|so.!(conf)|a|rpm|gif|GIF|jp?(e)g|JP?(E)G|mp3|MP3|mp?(e)g|MPG|avi|AVI|asf|ASF|ogg|OGG|class|CLASS)' vi vim gvim rvim view rview rgvim rgview gview
complete -f -X '*.@(o|so|so.!(conf)|a|rpm|gif|GIF|jp?(e)g|JP?(E)G|mp3|MP3|mp?(e)g|MPG|avi|AVI|asf|ASF|ogg|OGG|class|CLASS)' emacs
complete -f -X '!*.@(exe|EXE|com|COM|scr|SCR|exe.so)' wine
complete -f -X '!*.@(zip|ZIP|z|Z|gz|GZ|tgz|TGZ)' bzme
complete -f -X '!*.@(?([xX]|[sS])[hH][tT][mM]?([lL]))' netscape mozilla lynx opera galeon curl dillo elinks amaya
complete -f -X '!*.@(sxw|stw|sxg|sgl|doc|dot|rtf|txt|htm|html|odt|ott|odm)' oowriter
complete -f -X '!*.@(sxi|sti|pps|ppt|pot|odp|otp)' ooimpress
complete -f -X '!*.@(sxc|stc|xls|xlw|xlt|csv|ods|ots)' oocalc
complete -f -X '!*.@(sxd|std|sda|sdd|odg|otg)' oodraw
complete -f -X '!*.@(sxm|smf|mml|odf)' oomath
complete -f -X '!*.odb' oobase
complete -f -X '!*.rpm' rpm2cpio
complete -f -X '!*.sqlite' sqlite3
complete -f -X '!*.aux' bibtex
# FINISH exclude -- do not remove this line

# start of section containing compspecs that can be handled within bash

# user commands see only users
complete -u su passwd write chfn groups slay w sux

# bg completes with stopped jobs
complete -A stopped -P '"%' -S '"' bg

# other job commands
complete -j -P '"%' -S '"' fg jobs disown

# readonly and unset complete with shell variables
complete -v readonly unset

# set completes with set options
complete -A setopt set

# shopt completes with shopt options
complete -A shopt shopt

# helptopics
complete -A helptopic help

# unalias completes with aliases
complete -a unalias

# bind completes with readline bindings (make this more intelligent)
complete -A binding bind

# type and which complete on commands
complete -c command type which

# builtin completes on builtins
complete -b builtin

# start of section containing completion functions called by other functions

# This function checks whether we have a given program on the system.
# No need for bulky functions in memory if we don't.
#
have()
{
	unset -v have
	PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin type $1 &>/dev/null &&
		have="yes"
}

# use GNU sed if we have it, since its extensions are still used in our code
#
[ $USERLAND != GNU ] && have gsed && alias sed=gsed

# This function checks whether a given readline variable
# is `on'.
#
_rl_enabled()
{
    [[ "$( bind -v )" = *$1+([[:space:]])on* ]]
}

# This function shell-quotes the argument
quote()
{
	echo \'${1//\'/\'\\\'\'}\' #'# Help vim syntax highlighting
}

# This function quotes the argument in a way so that readline dequoting 
# results in the original argument
quote_readline()
{
	if [ -n "$bash4" ] ; then
		# This function isn't really necessary on bash 4
		# See: http://lists.gnu.org/archive/html/bug-bash/2009-03/msg00155.html
		echo "${1}"
		return
	fi
	local t="${1//\\/\\\\}"
	echo \'${t//\'/\'\\\'\'}\' #'# Help vim syntax highlighting
}

# This function shell-dequotes the argument
dequote()
{
	eval echo "$1"
}

# Get the word to complete
# This is nicer than ${COMP_WORDS[$COMP_CWORD]}, since it handles cases
# where the user is completing in the middle of a word.
# (For example, if the line is "ls foobar",
# and the cursor is here -------->   ^
# it will complete just "foo", not "foobar", which is what the user wants.)
#
#
# Accepts an optional parameter indicating which characters out of
# $COMP_WORDBREAKS should NOT be considered word breaks. This is useful
# for things like scp where we want to return host:path and not only path.
_get_cword()
{
	if [[ "${#COMP_WORDS[COMP_CWORD]}" -eq 0 ]] || [[ "$COMP_POINT" == "${#COMP_LINE}" ]]; then
		printf "%s" "${COMP_WORDS[COMP_CWORD]}"
	else
		local i
		local cur="$COMP_LINE"
		local index="$COMP_POINT"
		for (( i = 0; i <= COMP_CWORD; ++i )); do
			while [[ "${#cur}" -ge ${#COMP_WORDS[i]} ]] && [[ "${cur:0:${#COMP_WORDS[i]}}" != "${COMP_WORDS[i]}" ]]; do
				cur="${cur:1}"
				index="$(( index - 1 ))"
			done
			if [[ "$i" -lt "$COMP_CWORD" ]]; then
				local old_size="${#cur}"
				cur="${cur#${COMP_WORDS[i]}}"
				local new_size="${#cur}"
				index="$(( index - old_size + new_size ))"
			fi
		done
		
		if [[ "${COMP_WORDS[COMP_CWORD]:0:${#cur}}" != "$cur" ]]; then
			# We messed up! At least return the whole word so things 
			# keep working
			printf "%s" "${COMP_WORDS[COMP_CWORD]}"
		else
			printf "%s" "${cur:0:$index}"
		fi
	fi
}

# This function performs file and directory completion. It's better than
# simply using 'compgen -f', because it honours spaces in filenames.
# If passed -d, it completes only on directories. If passed anything else,
# it's assumed to be a file glob to complete on.
#
_filedir()
{
	local IFS=$'\t\n' xspec

	_expand || return 0

	local -a toks
	local tmp
	
	# TODO: I've removed a "[ -n $tmp ] &&" before `echo $tmp',
	#       and everything works again. If this bug
	#       suddenly appears again (i.e. "cd /b<TAB>"
	#       becomes "cd /"), remember to check for
	#       other similar conditionals (here and
	#       _filedir_xspec()). --David
	# NOTE: The comment above has been moved outside of the subshell below, 
	#       because quotes-in-comments-in-a-subshell cause errors on
	#       bash-3.1.  See also: 
	#       http://www.mail-archive.com/bug-bash@gnu.org/msg01667.html
	toks=( ${toks[@]-} $(
		compgen -d -- "$(quote_readline "$cur")" | {
			while read -r tmp; do
				echo $tmp
			done
		}
	))
	
	if [[ "$1" != -d ]]; then
		xspec=${1:+"!*.$1"}
		toks=( ${toks[@]-} $(
			compgen -f -X "$xspec" -- "$(quote_readline "$cur")" | {
				while read -r tmp; do
					[ -n $tmp ] && echo $tmp
				done
			}
		))
	fi

	COMPREPLY=( "${COMPREPLY[@]}" "${toks[@]}" )
}

# This function splits $cur=--foo=bar into $prev=--foo, $cur=bar, making it
# easier to support both "--foo bar" and "--foo=bar" style completions.
# Returns 0 if current option was split, 1 otherwise.
#
_split_longopt()
{
	if [[ "$cur" == --?*=* ]]; then
		# Cut also backslash before '=' in case it ended up there
		# for some reason.
		prev="${cur%%?(\\)=*}"
		cur="${cur#*=}"
		return 0
	fi

	return 1
}

# This function tries to parse the output of $command --help
#
_parse_help() {
	local cmd
	cmd=$1
	$cmd --help | \
		grep -- "^[[:space:]]*-" | \
		tr "," " " | \
		awk '{print $1; if ($2 ~ /-.*/) { print $2 } }' | \
		sed -e "s:=.*::g"
}

# This function completes on signal names
#
_signals()
{
	local i

	# standard signal completion is rather braindead, so we need
	# to hack around to get what we want here, which is to
	# complete on a dash, followed by the signal name minus
	# the SIG prefix
	COMPREPLY=( $( compgen -A signal SIG${cur#-} ))
	for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do
		COMPREPLY[i]=-${COMPREPLY[i]#SIG}
	done
}

# This function completes on configured network interfaces
#
_configured_interfaces()
{
	if [ -f /etc/debian_version ]; then
		# Debian system
		COMPREPLY=( $( sed -ne 's|^iface \([^ ]\+\).*$|\1|p' \
			       /etc/network/interfaces ) )
	elif [ -f /etc/SuSE-release ]; then
		# SuSE system
		COMPREPLY=( $( command ls \
			/etc/sysconfig/network/ifcfg-* | \
			sed -ne 's|.*ifcfg-\('$cur'.*\)|\1|p' ) )
	elif [ -f /etc/pld-release ]; then
		# PLD Linux
		COMPREPLY=( $( command ls -B \
			/etc/sysconfig/interfaces | \
			sed -ne 's|.*ifcfg-\('$cur'.*\)|\1|p' ) )
	else
		# Assume Red Hat
		COMPREPLY=( $( command ls \
			/etc/sysconfig/network-scripts/ifcfg-* | \
			sed -ne 's|.*ifcfg-\('$cur'.*\)|\1|p' ) )
	fi
}

# This function completes on available kernels
#
_kernel_versions()
{
	COMPREPLY=( $( compgen -W '$( command ls /lib/modules )' -- $cur ) )
}

# This function completes on all available network interfaces
# -a: restrict to active interfaces only
# -w: restrict to wireless interfaces only
#
_available_interfaces()
{
	local cmd

	if [ "${1:-}" = -w ]; then
		cmd="iwconfig"
	elif [ "${1:-}" = -a ]; then
		cmd="ifconfig"
	else
		cmd="ifconfig -a"
	fi

	COMPREPLY=( $( eval $cmd 2>/dev/null | \
		sed -ne 's|^\('$cur'[^[:space:][:punct:]]\{1,\}\).*$|\1|p') )
}

# This function expands tildes in pathnames
#
_expand()
{
	# FIXME: Why was this here?
	#[ "$cur" != "${cur%\\}" ] && cur="$cur\\"

	# Expand ~username type directory specifications.  We want to expand
	# ~foo/... to /home/foo/... to avoid problems when $cur starting with
	# a tilde is fed to commands and ending up quoted instead of expanded.

	if [[ "$cur" == \~*/* ]]; then
		eval cur=$cur
	elif [[ "$cur" == \~* ]]; then
		cur=${cur#\~}
		COMPREPLY=( $( compgen -P '~' -u $cur ) )
		[ ${#COMPREPLY[@]} -eq 1 ] && eval COMPREPLY[0]=${COMPREPLY[0]}
		return ${#COMPREPLY[@]}
	fi
}

# This function completes on process IDs.
# AIX and Solaris ps prefers X/Open syntax.
[ $UNAME = SunOS -o $UNAME = AIX ] &&
_pids()
{
	COMPREPLY=( $( compgen -W '$( command ps -efo pid | sed 1d )' -- $cur ))
} ||
_pids()
{
	COMPREPLY=( $( compgen -W '$( command ps axo pid | sed 1d )' -- $cur ) )
}

# This function completes on process group IDs.
# AIX and SunOS prefer X/Open, all else should be BSD.
[ $UNAME = SunOS -o $UNAME = AIX ] &&
_pgids()
{
	COMPREPLY=( $( compgen -W '$( command ps -efo pgid | sed 1d )' -- $cur ))
} ||
_pgids()
{
	COMPREPLY=( $( compgen -W '$( command ps axo pgid | sed 1d )' -- $cur ))
}

# This function completes on process names.
# AIX and SunOS prefer X/Open, all else should be BSD.
[ $UNAME = SunOS -o $UNAME = AIX ] &&
_pnames()
{
	COMPREPLY=( $( compgen -W '$( command ps -efo comm | \
			           sed -e 1d -e "s:.*/::" -e "s/^-//" \
				       -e "s/^<defunct>$//")' \
			           -- $cur ) )
} ||
_pnames()
{
	# FIXME: completes "[kblockd/0]" to "0". Previously it was completed
	# to "kblockd" which isn't correct either. "kblockd/0" would be
	# arguably most correct, but killall from psmisc 22 treats arguments
	# containing "/" specially unless -r is given so that wouldn't quite
	# work either. Perhaps it'd be best to not complete these to anything
	# for now.
	# Not using "ps axo comm" because under some Linux kernels, it
	# truncates command names (see e.g. http://bugs.debian.org/497540#19)
	COMPREPLY=( $( compgen -W '$( command ps axo command | \
			           sed -e "1d; s/ .*//; s:.*/::; s/:$//;" \
			               -e "s/^[[(-]//; s/[])]$//" \
				       -e "s/^<defunct>$//")' \
			           -- $cur ) )
}

# This function completes on user IDs
#
_uids()
{
	if type getent &>/dev/null; then
	    COMPREPLY=( $( compgen -W '$( getent passwd | cut -d: -f3 )' -- $cur ) )
	elif type perl &>/dev/null; then
	    COMPREPLY=( $( compgen -W '$( perl -e '"'"'while (($uid) = (getpwent)[2]) { print $uid . "\n" }'"'"' )' -- $cur ) )
	else
	    # make do with /etc/passwd
	    COMPREPLY=( $( compgen -W '$( cut -d: -f3 /etc/passwd )' -- $cur ) )
	fi
}

# This function completes on group IDs
#
_gids()
{
	if type getent &>/dev/null; then
	    COMPREPLY=( $( getent group | \
			    awk -F: '{if ($3 ~ /^'$cur'/) print $3}' ) )
	elif type perl &>/dev/null; then
	    COMPREPLY=( $( compgen -W '$( perl -e '"'"'while (($gid) = (getgrent)[2]) { print $gid . "\n" }'"'"' )' -- $cur ) )
	else
	    # make do with /etc/group
	    COMPREPLY=( $( awk 'BEGIN {FS=":"} {if ($3 ~ /^'$cur'/) print $3}'\
			    /etc/group ) )
	fi
}

# This function completes on services
#
_services()
{
	local sysvdir famdir
	[ -d /etc/rc.d/init.d ] && sysvdir=/etc/rc.d/init.d || sysvdir=/etc/init.d
	famdir=/etc/xinetd.d
	COMPREPLY=( $( builtin echo $sysvdir/!(*.rpm@(orig|new|save)|*~|functions)) )

	if [ -d $famdir ]; then
		COMPREPLY=( "${COMPREPLY[@]}" $( builtin echo $famdir/!(*.rpm@(orig|new|save)|*~)) )
	fi

	COMPREPLY=( $( compgen -W '${COMPREPLY[@]#@($sysvdir|$famdir)/}' -- $cur ) )
}

# This function completes on modules
#
_modules()
{
	local modpath
	modpath=/lib/modules/$1
	COMPREPLY=( $( command ls -R $modpath | \
			sed -ne 's/^\('$cur'.*\)\.k\?o\(\|.gz\)$/\1/p') )
}

# This function completes on installed modules
#
_installed_modules()
{
	COMPREPLY=( $( compgen -W "$( /sbin/lsmod | \
				  awk '{if (NR != 1) print $1}' )" -- $1 ) )
}

# This function completes on user:group format
#
_usergroup()
{
	local IFS=$'\n'
	cur=${cur//\\\\ / }
	if [[ $cur = *@(\\:|.)* ]] && [ -n "$bash205" ]; then
		user=${cur%%*([^:.])}
		COMPREPLY=( $(compgen -P ${user/\\\\} -g -- ${cur##*[.:]}) )
	elif [[ $cur = *:* ]] && [ -n "$bash205" ]; then
		COMPREPLY=( $( compgen -g -- ${cur##*[.:]} ) )
	else
		COMPREPLY=( $( compgen -S : -u -- $cur ) )
	fi
}

# This function completes on valid shells
#
_shells()
{
	COMPREPLY=( "${COMPREPLY[@]}" $( compgen -W '$( grep "^[[:space:]]*/" \
			/etc/shells 2>/dev/null )' -- $cur ) )
}

# Get real command.
# - arg: $1  Command
# - stdout:  Filename of command in PATH with possible symbolic links resolved.
#            Empty string if command not found.
# - return:  True (0) if command found, False (> 0) if not.
_realcommand() {
	type -P "$1" > /dev/null && {
		if type -p realpath > /dev/null; then
			realpath "$(type -P "$1")"
		elif type -p readlink > /dev/null; then
			readlink -f "$(type -P "$1")"
		else
			type -P "$1"
		fi
	}
}


# this function count the number of mandatory args
#
_count_args()
{
	args=1
	for (( i=1; i < COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" != -* ]]; then
			args=$(($args+1))
		fi
	done
}

# This function complete on PCI IDs
#
_pci_ids()
{
	COMPREPLY=( ${COMPREPLY[@]:-} \
		$( compgen -W "$( lspci -n | awk '{print $3}')" -- $cur ) )
}

# This function complete on USB IDs
#
_usb_ids()
{
	COMPREPLY=( ${COMPREPLY[@]:-} \
		$( compgen -W "$( lsusb | awk '{print $6}')" -- $cur ) )
}

# start of section containing completion functions for bash built-ins

# bash alias completion
#
_alias()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	case "$COMP_LINE" in
	*[^=])
		COMPREPLY=( $( compgen -A alias -- $cur ) )
		;;
	*=)
		COMPREPLY=( "$( alias ${cur%=} 2>/dev/null | \
			     sed -e 's|^alias '$cur'\(.*\)$|\1|' )" )
		;;
	esac
}
complete -F _alias $nospace alias

# bash export completion
#
_export()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	case "$COMP_LINE" in
	*=\$*)
		COMPREPLY=( $( compgen -v -P '$' -- ${cur#*=\$} ) )
		;;
	*[^=])
		COMPREPLY=( $( compgen -v -S '=' -- $cur ) )
		;;
	*=)
		COMPREPLY=( "$( eval echo -n \"$`echo ${cur%=}`\" |
			( echo -n \'
			  sed -e 's/'\''/'\''\\\'\'''\''/g'
			  echo -n \' ) )" )
		;;
	esac
}
complete -F _export $default $nospace export

# bash shell function completion
#
_function()
{
	local cur prev

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

	if [[ $1 == @(declare|typeset) ]]; then
		if [ "$prev" = -f ]; then
			COMPREPLY=( $( compgen -A function -- $cur ) )
		elif [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '-a -f -F -i -r -x -p' -- \
				       $cur ) )
		fi
	elif [ $COMP_CWORD -eq 1 ]; then
		COMPREPLY=( $( compgen -A function -- $cur ) )
	else
		COMPREPLY=( "() $( type -- ${COMP_WORDS[1]} | sed -e 1,2d )" )
	fi
}
complete -F _function function declare typeset

# bash complete completion
#
_complete()
{
	local cur prev options

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

	case $prev in
		-o)
			options="default dirnames filenames"
			[ -n "$bash205b" ] && options="$options nospace"
			[ -n "$bash3" ] && options="$options bashdefault plusdirs"
			COMPREPLY=( $( compgen -W "$options" -- $cur ) )
			return 0
			;;

		-A)
			COMPREPLY=( $( compgen -W 'alias arrayvar binding \
				builtin command directory disabled enabled \
				export file function group helptopic hostname \
				job keyword running service setopt shopt \
				signal stopped user variable' -- $cur ) )
			return 0
			;;

		-C)
			COMPREPLY=( $( compgen -A command -- $cur ) )
			return 0
			;;
		-F)
			COMPREPLY=( $( compgen -A function -- $cur ) )
			return 0
			;;
		-@(p|r))
			COMPREPLY=( $( complete -p | sed -e 's|.* ||' ) )
			COMPREPLY=( $( compgen -W '${COMPREPLY[@]}' -- $cur ) )
			return 0
			;;

	esac

	if [[ "$cur" == -* ]]; then
		# relevant options completion
		options="-a -b -c -d -e -f -g -j -k -s -v -u -A -G -W -P -S -X -F -C"
		[ -n "$bash205" ] && options="$options -o"
		COMPREPLY=( $( compgen -W "$options" -- $cur ) )
	else
		COMPREPLY=( $( compgen -A command -- $cur ) )
	fi
}
complete -F _complete complete

# start of section containing completion functions for external programs

# a little help for FreeBSD ports users
[ $UNAME = FreeBSD ] && complete -W 'index search fetch fetch-list \
	extract patch configure build install reinstall \
	deinstall clean clean-depends kernel buildworld' make

# This completes on a list of all available service scripts for the
# 'service' command and/or the SysV init.d directory, followed by
# that script's available commands
#
{ have service || [ -d /etc/init.d/ ]; } &&
_service()
{
	local cur sysvdir

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

	# don't complete for things like killall, ssh and mysql if it's
	# the standalone command, rather than the init script
	[[ ${COMP_WORDS[0]} != @(*init.d/!(functions|~)|service) ]] && return 0

	# don't complete past 2nd token
	[ $COMP_CWORD -gt 2 ] && return 0

	[ -d /etc/rc.d/init.d ] && sysvdir=/etc/rc.d/init.d \
				|| sysvdir=/etc/init.d

	if [[ $COMP_CWORD -eq 1 ]] && [[ $prev == "service" ]]; then
		_services
	else
		COMPREPLY=( $( compgen -W '`sed -ne "y/|/ /; \
				s/^.*Usage.*{\(.*\)}.*$/\1/p" \
				$sysvdir/${prev##*/} 2>/dev/null`' -- $cur ) )
	fi

	return 0
} &&
complete -F _service service
[ -d /etc/init.d/ ] && complete -F _service $default \
	$(for i in /etc/init.d/*; do echo ${i##*/}; done)

# chown(1) completion
#
_chown()
{
	local cur prev split=false
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	_split_longopt && split=true

	case "$prev" in
		--from)
			_usergroup
			return 0
			;;
		--reference)
			_filedir
			return 0
			;;
	esac

	$split && return 0

	# options completion
	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '-c -h -f -R -v --changes \
		--dereference --no-dereference --from --silent --quiet \
		--reference --recursive --verbose --help --version' -- $cur ) )
	else
		_count_args

		case $args in
			1)
				_usergroup
				;;
			*)
				_filedir
				;;
		esac
	fi
}
complete -F _chown $filenames chown

# chgrp(1) completion
#
_chgrp()
{
	local cur prev split=false

	COMPREPLY=()
	cur=`_get_cword`
	cur=${cur//\\\\/}
	prev=${COMP_WORDS[COMP_CWORD-1]}

	_split_longopt && split=true

	if [[ "$prev" == --reference ]]; then
		_filedir
		return 0
	fi

	$split && return 0
		
	# options completion
	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '-c -h -f -R -v --changes \
		--dereference --no-dereference --silent --quiet \
		--reference --recursive --verbose --help --version' -- $cur ) )
		return 0
	fi

	# first parameter on line or first since an option?
	if [ $COMP_CWORD -eq 1 ] && [[ "$cur" != -* ]] || \
	   [[ "$prev" == -* ]] && [ -n "$bash205" ]; then
		local IFS=$'\n'
		COMPREPLY=( $( compgen -g $cur 2>/dev/null ) )
	else
		_filedir || return 0
	fi

	return 0
}
complete -F _chgrp $filenames chgrp

# umount(8) completion. This relies on the mount point being the third
# space-delimited field in the output of mount(8)
#
_umount()
{
	local cur IFS=$'\n'

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( compgen -W '$( mount | cut -d" " -f 3 )' -- $cur ) )

	return 0
}
complete -F _umount $dirnames umount

# mount(8) completion. This will pull a list of possible mounts out of
# /etc/{,v}fstab, unless the word being completed contains a ':', which
# would indicate the specification of an NFS server. In that case, we
# query the server for a list of all available exports and complete on
# that instead.
#
_mount()
{
	local cur i sm host prev

	COMPREPLY=()
	cur=`_get_cword`
	[[ "$cur" == \\ ]] && cur="/"
	prev=${COMP_WORDS[COMP_CWORD-1]}

	for i in {,/usr}/{,s}bin/showmount; do [ -x $i ] && sm=$i && break; done

	if [ -n "$sm" ] && [[ "$cur" == *:* ]]; then
		COMPREPLY=( $( $sm -e ${cur%%:*} | sed 1d | \
			       grep ^${cur#*:} | awk '{print $1}' ) )
	elif [[ "$cur" == //* ]]; then
		host=${cur#//}
		host=${host%%/*}
		if [ -n "$host" ]; then
			COMPREPLY=( $( compgen -W "$( echo $( smbclient -d 0 -NL $host 2>/dev/null|
			sed -ne '/^['"$'\t '"']*Sharename/,/^$/p' |
			sed -ne '3,$s|^[^A-Za-z]*\([^'"$'\t '"']*\).*$|//'$host'/\1|p' ) )" -- "$cur" ) )
		fi
	elif [ -r /etc/vfstab ]; then
		# Solaris
		COMPREPLY=( $( compgen -W "$( awk '! /^[ \t]*#/ {if ($3 ~ /\//) print $3}' /etc/vfstab )" -- $cur ) )
	elif [ ! -e /etc/fstab ]; then
		# probably Cygwin
		COMPREPLY=( $( compgen -W "$( mount | awk '! /^[ \t]*#/ {if ($3 ~ /\//) print $3}' )" -- $cur ) )
	else
		# probably Linux
		if [ $prev = -L ]; then
			COMPREPLY=( $( compgen -W '$(sed -ne "s/^[[:space:]]*LABEL=\([^[:space:]]*\).*/\1/p" /etc/fstab )' -- $cur ) )
		elif [ $prev = -U ]; then
			COMPREPLY=( $( compgen -W '$(sed -ne "s/^[[:space:]]*UUID=\([^[:space:]]*\).*/\1/p" /etc/fstab )' -- $cur ) )
		else
			COMPREPLY=( $( compgen -W "$( awk '! /^[ \t]*#/ {if ($2 ~ /\//) print $2}' /etc/fstab )" -- $cur ) )
		fi
	fi

	return 0
}
complete -F _mount $default $dirnames mount

# Linux rmmod(8) completion. This completes on a list of all currently
# installed kernel modules.
#
have rmmod && {
_rmmod()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	_installed_modules "$cur"
	return 0
}
complete -F _rmmod rmmod

# Linux insmod(8), modprobe(8) and modinfo(8) completion. This completes on a
# list of all available modules for the version of the kernel currently
# running.
#
_insmod()
{
	local cur prev modpath

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

	# behave like lsmod for modprobe -r
	if [ $1 = "modprobe" ] &&
	   [ "${COMP_WORDS[1]}" = "-r" ]; then
		_installed_modules "$cur"
		return 0
	fi

	# do filename completion if we're giving a path to a module
	if [[ "$cur" == */* ]]; then
		_filedir '@(?(k)o?(.gz))'
		return 0
	fi

	if [ $COMP_CWORD -gt 1 ] &&
	   [[ "${COMP_WORDS[COMP_CWORD-1]}" != -* ]]; then
		# do module parameter completion
		COMPREPLY=( $( /sbin/modinfo -p ${COMP_WORDS[1]} 2>/dev/null | \
		       awk '{if ($1 ~ /^parm:/ && $2 ~ /^'$cur'/) { print $2 } \
			else if ($1 !~ /:/ && $1 ~ /^'$cur'/) { print $1 }}' ) )
	else
		_modules $(uname -r)
	fi

	return 0
}
complete -F _insmod $filenames insmod modprobe modinfo
}

# man(1) completion
#
[ $USERLAND = GNU -o $UNAME = Darwin \
  -o $UNAME = FreeBSD -o $UNAME = SunOS -o $UNAME = Cygwin \
  -o $UNAME = OpenBSD ] &&
_man()
{
	local cur prev sect manpath manext mansect uname

	manext="@([0-9lnp]|[0-9][px]|man)?(.@(gz|bz2|lzma))"
	mansect="@([0-9lnp]|[0-9][px])"

	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	
	if [[ "$prev" == -l ]]; then
		_filedir $manext
		return 0
	fi

	_expand || return 0

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

	uname=$( uname -s )
	if [[ $uname == @(Linux|GNU|GNU/*|FreeBSD|Cygwin|CYGWIN_*) ]]; then
		manpath=$( manpath 2>/dev/null || command man --path )
	else
		manpath=$MANPATH
	fi

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

	# determine manual section to search
	[[ "$prev" == $mansect ]] && 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)} )
	COMPREPLY=( $( compgen -W '${COMPREPLY[@]%.*}' -- "${cur//\\\\/}" ) )

	if [[ "$prev" != $mansect ]]; then
		# File based completion for the rest, prepending ./ if needed
		# (man 1.6f needs that for man pages in current dir)
		local start=${#COMPREPLY[@]}
		_filedir $manext
		for (( i=$start; i < ${#COMPREPLY[@]}; i++ )); do
			[[ ${COMPREPLY[i]} == */* ]] || COMPREPLY[i]=./${COMPREPLY[i]}
		done
	fi

	return 0
}
[ $USERLAND = GNU -o $UNAME = Darwin \
  -o $UNAME = FreeBSD -o $UNAME = SunOS -o $UNAME = Cygwin \
  -o $UNAME = OpenBSD ] && \
complete -F _man $filenames man apropos whatis

# renice(8) completion
#
_renice()
{
	local command cur curopt i

	COMPREPLY=()
	cur=`_get_cword`
	command=$1

	i=0
	# walk back through command line and find last option
	while [ $i -le $COMP_CWORD -a ${#COMPREPLY[@]} -eq 0 ]; do
		curopt=${COMP_WORDS[COMP_CWORD-$i]}
		case "$curopt" in
		-u)
			COMPREPLY=( $( compgen -u -- $cur ) )
			;;
		-g)
			_pgids
			;;
		-p|$command)
			_pids
			;;
		esac
		i=$(( ++i ))
	done
}
complete -F _renice renice

# kill(1) completion
#
_kill()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD -eq 1 ] && [[ "$cur" == -* ]]; then
		# return list of available signals
		_signals
	else
		# return list of available PIDs
		_pids
	fi
}
complete -F _kill kill

# killall(1) (Linux and FreeBSD) and pkill(1) completion.
#
[ $UNAME = Linux -o $UNAME = FreeBSD ] || have pkill &&
_killall()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD -eq 1 ] && [[ "$cur" == -* ]]; then
		_signals
	else
		_pnames
	fi

	return 0
}
[ $UNAME = Linux -o $UNAME = FreeBSD ] && complete -F _killall killall
have pkill && complete -F _killall pkill

# pgrep(1) completion.
#
[ $UNAME = Linux ] || have pgrep &&
_pgrep()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	_pnames

	return 0
}
have pgrep && complete -F _pgrep pgrep

# Linux pidof(8) completion.
[ $UNAME = Linux ] && complete -F _pgrep pidof

# Linux iwconfig(8) completion
#
[ $UNAME = Linux ] && have iwconfig &&
_iwconfig()
{
	local cur prev

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

	case $prev in
		mode)
			COMPREPLY=( $( compgen -W 'managed ad-hoc master \
				repeater secondary monitor' -- $cur ) )
			return 0
			;;
		essid)
			COMPREPLY=( $( compgen -W 'on off any' -- $cur ) )
			if [ -n "${COMP_IWLIST_SCAN:-}" ]; then
				COMPREPLY=( "${COMPREPLY[@]}" \
					$( iwlist ${COMP_WORDS[1]} scan | \
					awk -F '"' '/ESSID/ {print $2}' | \
					grep "^$cur" ))
			fi
			return 0
			;;
		nwid)
			COMPREPLY=( $( compgen -W 'on off' -- $cur ) )
			return 0
			;;
		channel)
			COMPREPLY=( $( iwlist ${COMP_WORDS[1]} channel | \
				awk '/^[[:space:]]*Channel/ {print $2}' | \
				grep "^$cur" ) )
			return 0
			;;

		freq)
			COMPREPLY=( $( iwlist ${COMP_WORDS[1]} channel | \
				awk '/^[[:space:]]*Channel/ {print $4"G"}' | \
				grep "^$cur" ) )
			return 0
			;;
		ap)
			COMPREPLY=( $( compgen -W 'on off any' -- $cur ) )
			if [ -n "${COMP_IWLIST_SCAN:-}" ]; then
				COMPREPLY=( "${COMPREPLY[@]}" \
					$( iwlist ${COMP_WORDS[1]} scan | \
					awk -F ': ' '/Address/ {print $2}' | \
					grep "^$cur" ) )
			fi
			return 0
			;;
		rate)
			COMPREPLY=( $( compgen -W 'auto fixed' -- $cur ) )
			COMPREPLY=( "${COMPREPLY[@]}" \
				$( iwlist ${COMP_WORDS[1]} rate | \
				awk '/^[[:space:]]*[0-9]/ {print $1"M"}' | \
				grep "^$cur" ) )
			return 0
			;;
		rts)
			COMPREPLY=( $( compgen -W 'auto fixed off' -- $cur ) )
			return 0
			;;
		frag)
			COMPREPLY=( $( compgen -W 'auto fixed off' -- $cur ) )
			return 0
			;;
		key)
			COMPREPLY=( $( compgen -W 'off on open restricted' -- $cur ) )
			return 0
			;;
		enc)
			COMPREPLY=( $( compgen -W 'off on open restricted' -- $cur ) )
			return 0
			;;
		power)
			COMPREPLY=( $( compgen -W 'period timeout off on' -- $cur ) )
			return 0
			;;
		txpower)
			COMPREPLY=( $( compgen -W 'off on auto' -- $cur ) )
			return 0
			;;
		retry)
			COMPREPLY=( $( compgen -W 'limit lifetime' -- $cur ) )
			return 0
			;;
	esac

	if [ $COMP_CWORD -eq 1 ]; then
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--help --version' -- $cur ) )
		else
			_available_interfaces -w
		fi
	else
		COMPREPLY=( $( compgen -W 'essid nwid mode freq channel sens mode \
			ap nick rate rts frag enc key power txpower commit' -- $cur ) )
	fi

} &&
complete -F _iwconfig iwconfig

# Linux iwlist(8) completion
#
[ $UNAME = Linux ] && have iwlist &&
_iwlist()
{
	local cur prev

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

	if [ $COMP_CWORD -eq 1 ]; then
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--help --version' -- $cur ) )
		else
			_available_interfaces -w
		fi
	else
		COMPREPLY=( $( compgen -W 'scan scanning freq frequency \
			channel rate bit bitrate key enc encryption power \
			txpower retry ap accesspoint peers event' -- $cur ) )
	fi
} &&
complete -F _iwlist iwlist

# Linux iwspy(8) completion
#
[ $UNAME = Linux ] && have iwspy &&
_iwspy()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD -eq 1 ]; then
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--help --version' -- $cur ) )
		else
			_available_interfaces -w
		fi
	else
		COMPREPLY=( $( compgen -W 'setthr getthr off' -- $cur ) )
	fi
} &&
complete -F _iwspy iwspy

# Linux iwpriv(8) completion
#
[ $UNAME = Linux ] && have iwpriv &&
_iwpriv()
{
	local cur prev

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

	case "$prev" in
		roam)
			COMPREPLY=( $( compgen -W 'on off' -- $cur ) )
			return 0
			;;
		port)
			COMPREPLY=( $( compgen -W 'ad-hoc managed' -- $cur ) )
			return 0
			;;
	esac

	if [ $COMP_CWORD -eq 1 ]; then
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--help --version' -- $cur ) )
		else
			_available_interfaces -w
		fi
	else
		COMPREPLY=( $( compgen -W '--all roam port' -- $cur ) )
	fi
} &&
complete -F _iwpriv iwpriv

# Red Hat & Debian GNU/Linux if{up,down} completion
#
[ $USERLAND = GNU ] && { have ifup || have ifdown; } &&
_ifupdown()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD -eq 1 ]; then
		_configured_interfaces
		COMPREPLY=( $(compgen -W '${COMPREPLY[@]}' -- "$cur") )
       fi

       return 0
} &&
complete -F _ifupdown ifup ifdown
[ $USERLAND = GNU ] && have ifstatus && complete -F _ifupdown ifstatus

# Linux ipsec(8) completion (for FreeS/WAN)
#
[ $UNAME = Linux ] && have ipsec &&
_ipsec()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`


	if [ $COMP_CWORD -eq 1 ]; then
		COMPREPLY=( $( compgen -W 'auto barf eroute klipsdebug look \
					   manual pluto ranbits rsasigkey \
					   setup showdefaults showhostkey spi \
					   spigrp tncfg whack' -- $cur ) )
		return 0
	fi

	case ${COMP_WORDS[1]} in
	auto)
		COMPREPLY=( $( compgen -W '--asynchronous --up --add --delete \
					   --replace --down --route --unroute \
					   --ready --status --rereadsecrets' \
					-- $cur ) )
		;;
	manual)
		COMPREPLY=( $( compgen -W '--up --down --route --unroute \
					   --union' -- $cur ) )
		;;
	ranbits)
		COMPREPLY=( $( compgen -W '--quick --continuous --bytes' \
					  -- $cur ) )
		;;
	setup)
		COMPREPLY=( $( compgen -W '--start --stop --restart' -- $cur ) )
		;;

	*)
		;;
	esac

	return 0
} &&
complete -F _ipsec ipsec

# cvs(1) completion
#
have cvs && {
set_prefix()
{
	[ -z ${prefix:-} ] || prefix=${cur%/*}/
	[ -r ${prefix:-}CVS/Entries ] || prefix=""
}

get_entries()
{
	local IFS=$'\n'
	[ -r ${prefix:-}CVS/Entries ] && \
	entries=$(cut -d/ -f2 -s ${prefix:-}CVS/Entries)
}

get_modules()
{
	if [ -n "$prefix" ]; then
		COMPREPLY=( $( command ls -d ${cvsroot}/${prefix}/!(CVSROOT) ) )
	else
		COMPREPLY=( $( command ls -d ${cvsroot}/!(CVSROOT) ) )
	fi
}

_cvs()
{
	local cur count mode i cvsroot cvsroots pwd
	local -a flags miss files entries changed newremoved

	COMPREPLY=()
	cur=`_get_cword`

	count=0
	for i in "${COMP_WORDS[@]}"; do
		[ $count -eq $COMP_CWORD ] && break
		# Last parameter was the CVSROOT, now go back to mode selection
		if [ "${COMP_WORDS[((count))]}" == "$cvsroot" -a "$mode" == "cvsroot" ]; then
			mode=""
		fi
		if [ -z "$mode" ]; then
			case $i in
			-d)
				mode=cvsroot
				cvsroot=${COMP_WORDS[((count+1))]}
				;;
			@(ad?(d)|new))
				mode=add
				;;
			@(adm?(in)|rcs))
				mode=admin
				;;
			ann?(notate))
				mode=annotate
				;;
			@(checkout|co|get))
				mode=checkout
				;;
			@(com?(mit)|ci))
				mode=commit
				;;
			di?(f?(f)))
				mode=diff
				;;
			ex?(p?(ort)))
				mode=export
				;;
			?(un)edit)
				mode=$i
				;;
			hi?(s?(tory)))
				mode=history
				;;
			im?(p?(ort)))
				mode=import
				;;
			re?(l?(ease)))
				mode=release
				;;
			?(r)log)
				mode=log
				;;
			@(rdiff|patch))
				mode=rdiff
				;;
			@(remove|rm|delete))
				mode=remove
				;;
			@(rtag|rfreeze))
				mode=rtag
				;;
			st?(at?(us)))
				mode=status
				;;
			@(tag|freeze))
				mode=tag
				;;
			up?(d?(ate)))
				mode=update
				;;
			*)
				;;
			esac
		elif [[ "$i" = -* ]]; then
			flags=( "${flags[@]}" $i )
		fi
		count=$((++count))
	done

	case "$mode" in
	add)
		if [[ "$cur" != -* ]]; then
			set_prefix
			if [ $COMP_CWORD -gt 1 -a -r ${prefix:-}CVS/Entries ]; then
				get_entries
				[ -z "$cur" ] && \
				files=$( command ls -Ad !(CVS) ) || \
				files=$( command ls -d ${cur}* 2>/dev/null )
				for i in "${entries[@]}"; do
					files=( ${files[@]/#$i//} )
				done
				COMPREPLY=( $( compgen -X '*~' -W '${files[@]}' -- \
					       $cur ) )
			fi
		else
			COMPREPLY=( $( compgen -W '-k -m' -- $cur ) )
		fi
		;;
	admin)
		if [[ "$cur" = -* ]]; then
			COMPREPLY=( $( compgen -W '-i -a -A -e -b -c -k -l -u \
						   -L -U -m -M -n -N -o -q -I \
						   -s -t -t- -T -V -x -z' -- \
					$cur ) )
		fi
		;;
	annotate)
		if [[ "$cur" = -* ]]; then
			COMPREPLY=( $( compgen -W '-D -F -f -l -R -r' -- $cur ) )
		else
			get_entries
			COMPREPLY=( $( compgen -W '${entries[@]}' -- $cur ) )
		fi
		;;
	checkout)
		if [[ "$cur" != -* ]]; then
			[ -z "$cvsroot" ] && cvsroot=$CVSROOT
			COMPREPLY=( $( cvs -d "$cvsroot" co -c 2> /dev/null | \
					awk '{print $1}' ) )
			COMPREPLY=( $( compgen -W '${COMPREPLY[@]}' -- $cur ) )
		else
			COMPREPLY=( $( compgen -W '-A -N -P -R -c -f -l -n -p \
						  -s -r -D -d -k -j' -- $cur ) )
		fi
		;;
	commit)
		set_prefix

		if [[ "$cur" != -* ]] && [ -r ${prefix:-}CVS/Entries ]; then
			# if $COMP_CVS_REMOTE is not null, 'cvs commit' will
			# complete on remotely checked-out files (requires
			# passwordless access to the remote repository
			if [ -n "${COMP_CVS_REMOTE:-}" ]; then
				# this is the least computationally intensive
				# way found so far, but other changes
				# (something other than changed/removed/new)
				# may be missing
				changed=( $( cvs -q diff --brief 2>&1 | \
				sed -ne 's/^Files [^ ]* and \([^ ]*\) differ$/\1/p' ) )
				newremoved=( $( cvs -q diff --brief 2>&1 | \
				sed -ne 's/^cvs diff: \([^ ]*\) .*, no comparison available$/\1/p' ) )
				COMPREPLY=( $( compgen -W '${changed[@]:-} \
						   ${newremoved[@]:-}' -- $cur ) )
			else
				COMPREPLY=( $(compgen $default -- "$cur") )
			fi
		else
			COMPREPLY=( $( compgen -W '-n -R -l -f -F -m -r' -- \
				       $cur ) )
		fi
		;;
	cvsroot)
		if [ -r ~/.cvspass ]; then
			# Ugly escaping because of bash treating ':' specially
			cvsroots=$( sed 's/^[^ ]* //; s/:/\\:/g' ~/.cvspass )
			COMPREPLY=( $( compgen -W '$cvsroots' -- $cur ) )
		fi
		;;
	export)
		if [[ "$cur" != -* ]]; then
			[ -z "$cvsroot" ] && cvsroot=$CVSROOT
			COMPREPLY=( $( cvs -d "$cvsroot" co -c | awk '{print $1}' ) )
			COMPREPLY=( $( compgen -W '${COMPREPLY[@]}' -- $cur ) )
		else
			COMPREPLY=( $( compgen -W '-N -f -l -R -n \
						  -r -D -d -k' -- $cur ) )
		fi
		;;
	diff)
		if [[ "$cur" == -* ]]; then
			_longopt diff
		else
			get_entries
			COMPREPLY=( $( compgen -W '${entries[@]:-}' -- $cur ) )
		fi
		;;
	remove)
		if [[ "$cur" != -* ]]; then
			set_prefix
			if [ $COMP_CWORD -gt 1 -a -r ${prefix:-}CVS/Entries ]; then
				get_entries
				# find out what files are missing
				for i in "${entries[@]}"; do
					[ ! -r "$i" ] && miss=( "${miss[@]}" $i )
				done
				COMPREPLY=( $(compgen -W '${miss[@]:-}' -- $cur) )
			fi
		else
			COMPREPLY=( $( compgen -W '-f -l -R' -- $cur ) )
		fi
		;;
	import)
		if [[ "$cur" != -* ]]; then
			# starts with same algorithm as checkout
			[ -z "$cvsroot" ] && cvsroot=$CVSROOT
			prefix=${cur%/*}
			if [ -r ${cvsroot}/${prefix} ]; then
				get_modules
				COMPREPLY=( ${COMPREPLY[@]#$cvsroot} )
				COMPREPLY=( ${COMPREPLY[@]#\/} )
			fi
			pwd=$( pwd )
			pwd=${pwd##*/}
			COMPREPLY=( $( compgen -W '${COMPREPLY[@]} $pwd' -- \
				       $cur ) )
		else
			COMPREPLY=( $( compgen -W '-d -k -I -b -m -W' -- $cur ))
		fi
		;;
	update)
		if [[ "$cur" = -* ]]; then
			COMPREPLY=( $( compgen -W '-A -P -C -d -f -l -R -p \
						   -k -r -D -j -I -W' -- \
						   $cur ) )
		fi
		;;
	"")
		COMPREPLY=( $( compgen -W 'add admin annotate checkout ci co \
					   commit diff delete edit export \
					   freeze get history import log new \
					   patch rcs rdiff release remove \
					   rfreeze rlog rm rtag stat status \
					   tag unedit up update -H -Q -q -b \
					   -d -e -f -l -n -t -r -v -w -x -z \
					   --help --version' -- $cur ) )
		;;
	*)
		;;
	esac

	return 0
}
complete -F _cvs $default cvs
}

have rpm && {
# helper functions for rpm completion
#
_rpm_installed_packages()
{
	local ver nodig="$1" nosig="$2"

	if [ -r /var/log/rpmpkgs -a \
		/var/log/rpmpkgs -nt /var/lib/rpm/Packages ]; then
		# using RHL 7.2 or later - this is quicker than querying the DB
		COMPREPLY=( $( sed -ne \
		's|^\('$cur'[^[:space:]]*\)-[^[:space:]-]\+-[^[:space:]-]\+\.rpm$|\1|p' \
				/var/log/rpmpkgs ) )
	else
		_rpm_nodigsig
		COMPREPLY=( $( rpm -qa $nodig $nosig --qf='%{NAME} ' "$cur*" ) )
	fi
}

_rpm_groups()
{
	local IFS=$'\t'
	# remove trailing backslash, or grep will complain
	cur=${cur%"\\"}
	COMPREPLY=( $( rpm -qa $nodig $nosig --queryformat '%{group}\n' | \
		       grep "^$cur" ) )
	# backslash escape spaces and translate newlines to tabs
	COMPREPLY=( $( echo "${COMPREPLY[@]}" | sed 's/ /\\ /g' | tr '\n' '\t' ) )
}

_rpm_nodigsig()
{
	if [ -z "$nodig" -a -z "$nosig" ]; then
		local rpmver
	
		rpmver=$(rpm --version)
		rpmver=${rpmver##* }

		if [[ "$rpmver" > "4.0.4" ]]; then
			nodig="--nodigest"
		fi
		if [[ "$rpmver" > "4.0.99" ]]; then
			nosig="--nosignature"
		fi
	fi
}

# rpm(8) completion
#
_rpm()
{
	local cur prev nodig nosig

	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	nodig=""
	nosig=""
	_rpm_nodigsig

	if [ $COMP_CWORD -eq 1 ]; then
		# first parameter on line
		case "$cur" in
		-b*)
			COMPREPLY=( $( compgen -W '-ba -bb -bc -bi -bl -bp -bs'\
				       -- $cur ) )
			;;
		-t*)
			COMPREPLY=( $( compgen -W '-ta -tb -tc -ti -tl -tp -ts'\
				       -- $cur ) )
			;;
		--*)
			COMPREPLY=( $( compgen -W '--help --version --initdb \
			--checksig --recompile --rebuild --resign --addsign \
			--rebuilddb --showrc --setperms --setugids --tarbuild \
			--eval --install --upgrade --query --freshen --erase \
			--verify --querytags --rmsource --rmspec --clean \
			--import' -- $cur ) )
			;;
		*)
			COMPREPLY=( $( compgen -W '-b -e -E -F -i -q -t -U -V' \
				       -- $cur ) )
			;;
		esac

	return 0
	fi

	case "$prev" in
	--@(@(db|exclude)path|prefix|relocate|root))
		_filedir -d
		return 0
		;;
	--eval|-E)
		# get a list of macros
		COMPREPLY=( $( rpm --showrc | sed -ne \
		's/^-\?[0-9]\+[:=][[:space:]]\+\('${cur#%}'[^[:space:](]*\).*/\1/p' ) )
		COMPREPLY=( "${COMPREPLY[@]/#/%}" )
		return 0
		;;
	--pipe)
		COMPREPLY=( $( compgen -c -- $cur ) )
		return 0
		;;
	--rcfile)
		_filedir
		return 0
		;;
	--specfile)
		# complete on .spec files
		_filedir spec
		return 0
		;;
	--whatprovides)
		if [[ "$cur" == */* ]]; then
			_filedir
		else
			# complete on capabilities
			local IFS=$'\n'
			COMPREPLY=( $( compgen -W "$( rpm -qa $nodig $nosig \
					--queryformat='%{providename}\n' )" \
					-- $cur ) )
		fi
		return 0
		;;
	--whatrequires)
		if [[ "$cur" == */* ]]; then
			_filedir
		else
			# complete on capabilities
			local IFS=$'\n'
			COMPREPLY=( $( compgen -W "$( rpm -qa $nodig $nosig \
					--queryformat='%{requirename}\n' )" \
					-- $cur ) )
		fi
		return 0
		;;
	--target)
		COMPREPLY=( $( compgen -W "$( command rpm --showrc | sed -ne \
		's/^\s*compatible\s\+build\s\+archs\s*:\s*\(.*\)/\1/ p' )" -- $cur ) )
		return 0
		;;
	esac

	case "${COMP_WORDS[1]}" in
	-@([iFU]*|-install|-freshen|-upgrade))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--percent --force --test \
			--replacepkgs --replacefiles --root --excludedocs \
			--includedocs --noscripts --rcfile --ignorearch \
			--dbpath --prefix --ignoreos --nodeps --allfiles \
			--ftpproxy --ftpport --justdb --httpproxy --httpport \
			--noorder --relocate --badreloc --notriggers \
			--excludepath --ignoresize --oldpackage --define \
			--eval --pipe --queryformat --repackage --nosuggests \
			--nodigest --nosignature' -- $cur ) )
		else
			_filedir 'rpm'
		fi
		;;
	-@(e|-erase))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--allmatches --noscripts \
			--notriggers --nodeps --test --repackage' -- $cur ) )
		else
			_rpm_installed_packages "$nodig" "$nosig"
		fi
		;;
	-@(q*|-query))
		# check whether we're doing file completion
		if [ "${COMP_LINE#* -*([^ -])f}" != "$COMP_LINE" ]; then
		    if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--scripts --root \
				--rcfile --requires --ftpport --ftpproxy \
				--httpproxy --httpport --provides --triggers \
				--dump --changelog --dbpath \
				--last --filesbypkg \
				--info --list --state \
				--docfiles --configfiles --queryformat \
				--conflicts --obsoletes \
				--nodigest --nosignature \
				--suggests --enhances \
				--triggerscripts' -- $cur ) )
		    else
			_filedir
		    fi
		elif [ "${COMP_LINE#* -*([^ -])g}" != "$COMP_LINE" ]; then
			_rpm_groups
		elif [ "${COMP_LINE#* -*([^ -])p}" != "$COMP_LINE" ]; then
			# uninstalled package completion
			if [[ "$cur" == -* ]]; then
				COMPREPLY=( $( compgen -W '--scripts --root \
				--rcfile --whatprovides --whatrequires \
				--requires --triggeredby --ftpport --ftpproxy \
				--httpproxy --httpport --provides --triggers \
				--dump --changelog --dbpath --filesbypkg \
				--define --eval --pipe --showrc --info --list \
				--state --docfiles --configfiles --queryformat\
				--conflicts --obsoletes --nodigest \
				--nosignature' -- $cur ) )
			else
				_filedir 'rpm'
			fi
		else
			# installed package completion
			if [[ "$cur" == -* ]]; then
				COMPREPLY=( $( compgen -W '--scripts --root \
				--rcfile --whatprovides --whatrequires \
				--requires --triggeredby --ftpport --ftpproxy \
				--httpproxy --httpport --provides --triggers \
				--dump --changelog --dbpath --specfile \
				--querybynumber --last --filesbypkg --define \
				--eval --pipe --showrc --info --list --state \
				--docfiles --configfiles --queryformat \
				--conflicts --obsoletes --pkgid --hdrid \
				--fileid --tid --nodigest --nosignature \
				--triggerscripts' -- $cur ) )
			elif [ "${COMP_LINE#* -*([^ -])a}" == "$COMP_LINE" ]; then
				_rpm_installed_packages "$nodig" "$nosig"
			fi
		fi
		;;
	-@(K*|-checksig))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--nopgp --nogpg --nomd5 \
					--nodigest --nosignature' -- $cur ) )
		else
			_filedir 'rpm'
		fi
		;;
	-@([Vy]*|-verify))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--root --rcfile --dbpath \
			--nodeps --nogroup --nolinkto --nomode --nomtime \
			--nordev --nouser --nofiles --noscripts --nomd5 \
			--querytags --specfile --whatrequires --whatprovides \
			--nodigest --nosignature' -- $cur ) )
		# check whether we're doing file completion
		elif [ "${COMP_LINE#* -*([^ -])f}" != "$COMP_LINE" ]; then
			_filedir
		elif [ "${COMP_LINE#* -*([^ -])g}" != "$COMP_LINE" ]; then
			_rpm_groups
		elif [ "${COMP_LINE#* -*([^ -])p}" != "$COMP_LINE" ]; then
			_filedir 'rpm'
		else
			_rpm_installed_packages "$nodig" "$nosig"
		fi
		;;
	-[bt]*)
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--short-circuit --timecheck \
			--clean --rmsource --rmspec --test --sign --buildroot \
			--target --nobuild --nodeps --nodirtokens' -- $cur ) )
		elif [[ ${COMP_WORDS[1]} == -b* ]]; then
			_filedir 'spec'
		else
			_filedir '@(tgz|tar.@(gz|bz2|lzma))'
		fi
		;;
	--re@(build|compile))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--nodeps --rmsource \
			  --rmspec --sign --nodirtokens --target' -- $cur ) )
		else
			_filedir '?(no)src.rpm'
		fi
		;;
	--tarbuild)
		_filedir '@(tgz|tar.@(gz|bz2|lzma))'
		;;
	--@(re|add)sign)
		_filedir 'rpm'
		;;
	--set@(perms|gids))
		_rpm_installed_packages "$nodig" "$nosig"
		;;
	--@(clean|rms@(ource|pec)))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--clean --rmsource \
					--rmspec' -- $cur ) )
		else
			_filedir 'spec'
		fi
		;;
	--@(import|dbpath|root))
		if [[ "$cur" == -* ]]; then
			COMPREPLY=( $( compgen -W '--import --dbpath --root' \
					-- $cur ) )
		else
			_filedir
		fi
		;;
	esac

	return 0
}
complete -F _rpm $filenames rpm rpmbuild
}

# Debian apt-get(8) completion.
#
have apt-get &&
_apt_get()
{
	local cur prev special i

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

	for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
		if [[ ${COMP_WORDS[i]} == @(install|remove|autoremove|purge|source|build-dep) ]]; then
			special=${COMP_WORDS[i]}
		fi
	done

	if [ -n "$special" ]; then
		case $special in
		remove|autoremove|purge)
			if [ -f /etc/debian_version ]; then
				# Debian system
				COMPREPLY=( $( _comp_dpkg_installed_packages \
						$cur ) )
			else
				# assume RPM based
				_rpm_installed_packages
			fi
			return 0
			;;
		*)
			COMPREPLY=( $( apt-cache pkgnames $cur 2> /dev/null ) )
			return 0
			;;

		esac
	fi

	case "$prev" in
	    -@(c|-config-file))
 		     _filedir
		     return 0
		     ;;

	    -@(t|-target-release|-default-release))
		     COMPREPLY=( $( apt-cache policy | \
				    grep "release.o=Debian,a=$cur" | \
				    sed -e "s/.*a=\(\w*\).*/\1/" | uniq 2> /dev/null) )
		     return 0
		     ;;

	esac

	if [[ "$cur" == -* ]]; then

		COMPREPLY=( $( compgen -W '-d -f -h -v -m -q -s -y \
				-u -t -b -c -o --download-only --fix-broken \
				--help --version --ignore-missing \
				--fix-missing --no-download --quiet --simulate \
				--just-print --dry-run --recon --no-act --yes \
				--assume-yes --show-upgraded --only-source \
				--compile --build --ignore-hold \
				--target-release --no-upgrade --force-yes \
				--print-uris --purge --reinstall \
				--list-cleanup --default-release \
				--trivial-only --no-remove --diff-only \
				--no-install-recommends \
				--tar-only --config-file --option --auto-remove' -- $cur ) )
	else

		COMPREPLY=( $( compgen -W 'update upgrade dselect-upgrade \
				dist-upgrade install remove purge source build-dep \
				check clean autoclean autoremove' -- $cur ) )

	fi


	return 0
} &&
complete -F _apt_get $filenames apt-get

# Debian apt-cache(8) completion.
#
have apt-cache &&
_apt_cache()
{
	local cur prev special i

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


	if [ "$cur" != show ]; then
	    for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
		if [[ ${COMP_WORDS[i]} == @(add|depends|dotty|madison|policy|rdepends|show?(pkg|src|)) ]]; then
		    special=${COMP_WORDS[i]}
		fi
	    done
	fi


	if [ -n "$special" ]; then
	    case $special in
		add)
		    _filedir
		    return 0
		    ;;

		showsrc)
			COMPREPLY=( $( apt-cache dumpavail | \
							grep "^Source: $cur" | sort | \
							uniq | cut -f2 -d" " ) )
			return 0
			;;
		
 		*)
		    COMPREPLY=( $( apt-cache pkgnames $cur 2> /dev/null ) )
		    return 0
		    ;;

	    esac
	fi


	case "$prev" in
	     -@(c|p|s|-config-file|-@(pkg|src)-cache))
		     _filedir
		     return 0
		     ;;
	     search)
		     if [[ "$cur" != -* ]]; then
			    return 0
		     fi
		     ;;
	esac

	if [[ "$cur" == -* ]]; then

		COMPREPLY=( $( compgen -W '-h -v -p -s -q -i -f -a -g -c \
				-o --help --version --pkg-cache --src-cache \
				--quiet --important --full --all-versions \
				--no-all-versions --generate --no-generate \
				--names-only --all-names --recurse \
				--config-file --option --installed' -- $cur ) )
	else

		COMPREPLY=( $( compgen -W 'add gencaches show showpkg showsrc \
				stats dump dumpavail unmet search search \
				depends rdepends pkgnames dotty xvcg \
				policy madison' -- $cur ) )

	fi


	return 0
} &&
complete -F _apt_cache $filenames apt-cache


# Debian aptitude(1) completion
#
have aptitude && {
have grep-status && {
_comp_dpkg_hold_packages()
{
	grep-status -P -e "^$1" -a -FStatus 'hold' -n -s Package
}
} || {
_comp_dpkg_hold_packages()
{
	grep -B 2 'hold' /var/lib/dpkg/status | grep "Package: $1" \
		| cut -d\  -f2
}
}

_aptitude()
{
	local cur dashoptions prev special i

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


	dashoptions='-S -u -i -h --help --version -s --simulate -d \
		     --download-only -P --prompt -y --assume-yes -F \
		     --display-format -O --sort -w --width -f -r -g \
		     --with-recommends --with-suggests -R -G \
		     --without-recommends --without-suggests -t \
		     --target-release -V --show-versions -D --show-deps\
		     -Z -v --verbose --purge-unused --schedule-only'

	for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
	    if [[ ${COMP_WORDS[i]} == @(install|reinstall|hold|unhold|markauto|unmarkauto|dist-upgrade|full-upgrade|download|show|forbid-version|purge|remove|changelog|why|why-not|keep|keep-all|build-dep) ]]; then
		special=${COMP_WORDS[i]}
	    fi
	    #exclude some mutually exclusive options
	    [[ ${COMP_WORDS[i]} == '-u' ]] && dashoptions=${dashoptions/-i}
	    [[ ${COMP_WORDS[i]} == '-i' ]] && dashoptions=${dashoptions/-u}
	done

	if [[ -n "$special" ]]; then
	   case $special in
	       @(install|hold|markauto|unmarkauto|dist-upgrade|full-upgrade|download|show|changelog|why|why-not|build-dep))
		   COMPREPLY=( $( apt-cache pkgnames $cur 2> /dev/null ) )
		   return 0
		   ;;
	       @(purge|remove|reinstall|forbid-version))
  		   COMPREPLY=( $( _comp_dpkg_installed_packages $cur ) )
		   return 0
		   ;;
	       unhold)
  		   COMPREPLY=( $( _comp_dpkg_hold_packages $cur ) )
		   return 0
		   ;;

	   esac
	fi

	case $prev in
	    # don't complete anything if these options are found
	    @(autoclean|clean|forget-new|search|upgrade|safe-upgrade|update|keep-all))
		return 0
		;;

	    -S)
		_filedir
		return 0
		;;

	    -@(t|-target-release|-default-release))
		COMPREPLY=( $( apt-cache policy | \
		    grep "release.o=Debian,a=$cur" | \
		    sed -e "s/.*a=\(\w*\).*/\1/" | uniq 2> /dev/null ) )
		return 0
		;;

	esac

	if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W "$dashoptions" -- $cur ) )
	else
	    COMPREPLY=( $( compgen -W 'update upgrade safe-upgrade forget-new clean \
				       autoclean install reinstall remove \
				       hold unhold purge markauto unmarkauto why why-not \
				       dist-upgrade full-upgrade download search show \
				       forbid-version changelog keep-all build-dep' -- $cur ) )
	fi


	return 0
}
complete -F _aptitude $default aptitude
}

# Debian apt-build(1) completion.
#
have apt-build &&
_apt_build()
{
	local cur prev special i

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

	for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
		if [[ ${COMP_WORDS[i]} == @(install|remove|source|info|clean) ]]; then
			special=${COMP_WORDS[i]}
		fi
	done

	if [ -n "$special" ]; then
		case $special in
		@(install|source|info))
			COMPREPLY=( $( apt-cache pkgnames $cur 2> /dev/null ) )
			return 0
			;;
		remove)
			COMPREPLY=( $( _comp_dpkg_installed_packages \
					$cur ) )
			return 0
			;;
		*)
			return 0
			;;
		esac
	fi

	case "$prev" in

	     --@(patch|build-dir|repository-dir))
		   _filedir
		   return 0
		   ;;

	     -@(h|-help))
		   return 0
		   ;;

	esac

	if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W '--help --show-upgraded -u --build-dir \
				  --repository-dir --build-only \
				  --build-command --reinstall --rebuild \
				  --remove-builddep --no-wrapper --purge \
				  --patch --patch-strip -p --yes -y \
				  --version -v --no-source' -- $cur ) )

	else
	    COMPREPLY=( $( compgen -W 'update upgrade install remove \
				  source dist-upgrade world clean info \
				  clean-build update-repository ' -- $cur ) )
	fi


	return 0
} &&
complete -F _apt_build $filenames apt-build

# chsh(1) completion
#
_chsh()
{
	local cur prev

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

	if [ "$prev" = "-s" ]; then
		_shells
	else
		COMPREPLY=( $( compgen -u -- $cur ) )
	fi

	return 0
}
complete -F _chsh chsh

# chkconfig(8) completion
#
have chkconfig &&
_chkconfig()
{
	local cur prev split=false

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

	_split_longopt && split=true

	case "$prev" in
	@(?(--level=)[1-6]|--@(list|add|del|override)))
		_services
		return 0
		;;
	--level)
		COMPREPLY=( $( compgen -W '1 2 3 4 5 6' -- $cur ) )
		return 0
		;;
	esac

	$split && return 0

	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '--list --add --del --override \
						--level' -- $cur ) )
	else
		if [ $COMP_CWORD -eq 2 -o $COMP_CWORD -eq 4 ]; then
			COMPREPLY=( $( compgen -W 'on off reset \
						resetpriorities' -- $cur ) )
		else
			_services
		fi
	fi
} &&
complete -F _chkconfig chkconfig

# This function provides simple user@host completion
#
_user_at_host() {
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [[ $cur == *@* ]]; then
		_known_hosts
	else
		COMPREPLY=( $( compgen -u -- "$cur" ) )
	fi

	return 0
}
shopt -u hostcomplete && complete -F _user_at_host $nospace talk ytalk finger

# This function performs host completion based on ssh's known_hosts files,
# defaulting to standard host completion if they don't exist.
#
# Arguments:  -a             Use aliases
#             -c             Use `:' suffix
#             -F configfile  Use `configfile' for configuration settings
#             -h host	     Complete on given host
_known_hosts()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	_known_hosts_real $@
}

_known_hosts_real()
{
	local configfile
	local curd ocur user suffix aliases global_kh user_kh hosts i host
	local -a kh khd config
	local IFS=$'\n'

	local OPTIND=1
	while getopts "acF:" flag "$@"; do
		case $flag in
			a) aliases='yes' ;;
			c) suffix=':' ;;
			F) configfile="$OPTARG" ;;
		esac
	done

	ocur=$cur
    
	[[ $cur == *@* ]] && user=${cur%@*}@ && cur=${cur#*@}
	kh=()

	# ssh config files
	if [ -n "$configfile" ]; then
		[ -r "$configfile" ] &&
		  config=( "${config[@]}" "$configfile" )
	else
		[ -r /etc/ssh/ssh_config ] &&
		  config=( "${config[@]}" "/etc/ssh/ssh_config" )
		[ -r "${HOME}/.ssh/config" ] &&
		  config=( "${config[@]}" "${HOME}/.ssh/config" )
		[ -r "${HOME}/.ssh2/config" ] &&
		  config=( "${config[@]}" "${HOME}/.ssh2/config" )
	fi

	if [ ${#config[@]} -gt 0 ]; then
		# expand path (if present) to global known hosts file
		global_kh=($( sed -ne 's/^[ \t]*[Gg][Ll][Oo][Bb][Aa][Ll][Kk][Nn][Oo][Ww][Nn][Hh][Oo][Ss][Tt][Ss][Ff][Ii][Ll][Ee]['"$'\t '"']*\(.*\)$/\1/p' "${config[@]}" ))
		for (( i=0; i < ${#global_kh[@]}; i++ )); do
			global_kh[i]=$(echo "${global_kh[i]//\"/}")
		done
		# expand path (if present) to user known hosts file
		user_kh=($( sed -ne 's/^[ \t]*[Uu][Ss][Ee][Rr][Kk][Nn][Oo][Ww][Nn][Hh][Oo][Ss][Tt][Ss][Ff][Ii][Ll][Ee]['"$'\t '"']*\(.*\)$/\1/p' "${config[@]}" ))
		for (( i=0; i < ${#user_kh[@]}; i++ )); do
			user_kh[i]=$(echo "${user_kh[i]//\"/}")
		done
	fi

	# Global known_hosts files
	[ -r "$global_kh" ] &&
		kh=( "${kh[@]}" "${global_kh[@]}" )
	if [ -z "$configfile" ]; then
		[ -r /etc/ssh/ssh_known_hosts ] &&
		  kh=( "${kh[@]}" /etc/ssh/ssh_known_hosts )
		[ -r /etc/ssh/ssh_known_hosts2 ] &&
		  kh=( "${kh[@]}" /etc/ssh/ssh_known_hosts2 )
		[ -r /etc/known_hosts ] &&
		  kh=( "${kh[@]}" /etc/known_hosts )
		[ -r /etc/known_hosts2 ] &&
		  kh=( "${kh[@]}" /etc/known_hosts2 )
		[ -d /etc/ssh2/knownhosts ] &&
		  khd=( "${khd[@]}" /etc/ssh2/knownhosts/*pub )
	fi

	# User known_hosts files
	[ -r "$user_kh" ] &&
		kh=( "${kh[@]}" "${user_kh[@]}" )
	if [ -z "$configfile" ]; then
		[ -r ~/.ssh/known_hosts ] &&
		  kh=( "${kh[@]}" ~/.ssh/known_hosts )
		[ -r ~/.ssh/known_hosts2 ] &&
		  kh=( "${kh[@]}" ~/.ssh/known_hosts2 )
		[ -d ~/.ssh2/hostkeys ] &&
		  khd=( "${khd[@]}" ~/.ssh2/hostkeys/*pub )
	fi

	# If we have known_hosts files to use
	if [ ${#kh[@]} -gt 0 -o ${#khd[@]} -gt 0 -o -n "$configfile" ]; then
	    # Escape slashes and dots in paths for awk
	    cur=${cur//\//\\\/}
	    cur=${cur//\./\\\.}
	    curd=$cur

	    if [[ "$cur" == [0-9]*.* ]]; then
		# Digits followed by a dot - just search for that
		cur="^$cur.*"
	    elif [[ "$cur" == [0-9]* ]]; then
		# Digits followed by no dot - search for digits followed
		# by a dot
		cur="^$cur.*\."
	    elif [ -z "$cur" ]; then
		# A blank - search for a dot or an alpha character
		cur="[a-z.]"
	    else
		cur="^$cur"
	    fi

	    if [ ${#kh[@]} -gt 0 ]; then

		# FS needs to look for a comma separated list
		COMPREPLY=( $( awk 'BEGIN {FS=","}
				/^\s*[^|\#]/ {for (i=1; i<=2; ++i) { \
				       gsub(" .*$", "", $i); \
				       if ($i ~ /'$cur'/) {print $i} \
				}}' "${kh[@]}" 2>/dev/null ) )
	    fi
	    if [ ${#khd[@]} -gt 0 ]; then
		# Needs to look for files called
		# .../.ssh2/key_22_<hostname>.pub
		# dont fork any processes, because in a cluster environment,
		# there can be hundreds of hostkeys
		for i in "${khd[@]}" ; do
		    if [[ "$i" == *key_22_$curd*.pub ]] && [ -r "$i" ] ; then
			host=${i/#*key_22_/}
			host=${host/%.pub/}
			COMPREPLY=( "${COMPREPLY[@]}" $host )
		    fi
		done
	    fi
	    # append any available aliases from config files
	    if [ ${#config[@]} -gt 0 ] && [ -n "$aliases" ]; then
	    local host_aliases=$( sed -ne 's/^[ \t]*[Hh][Oo][Ss][Tt]\([Nn][Aa][Mm][Ee]\)\?['"$'\t '"']\+\([^#*?]*\)\(#.*\)\?$/\2/p' "${config[@]}" )
	    hosts=$( compgen -W "$host_aliases" -- $ocur )
		COMPREPLY=( "${COMPREPLY[@]}" $hosts )
	    fi

	    # Now add results of normal hostname completion
	    COMPREPLY=( "${COMPREPLY[@]}" $( compgen -A hostname -- $ocur ) )

	    # apply suffix
	    for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do
		COMPREPLY[i]=$user${COMPREPLY[i]}$suffix
	    done
	elif [ -z "$configfile" ]; then
	    # Just do normal hostname completion
	    COMPREPLY=( $( compgen -A hostname -S "$suffix" -- $cur ) )
	fi

	return 0
}
complete -F _known_hosts traceroute traceroute6 tracepath tracepath6 \
	ping ping6 fping fping6 telnet host nslookup rsh rlogin ftp dig ssh-installkeys mtr

# Linux route(8) completion
#
[ $UNAME = Linux ] &&
_route()
{
	local cur prev

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

	if [ "$prev" = dev ]; then
	    COMPREPLY=( $( ifconfig -a | sed -ne 's|^\('$cur'[^ ]*\).*$|\1|p' ))
	    return 0
	fi

	COMPREPLY=( $( compgen -W 'add del -host -net netmask metric mss \
				   window irtt reject mod dyn reinstate dev \
				   default gw' -- $cur ) )

	COMPREPLY=( $( echo " ${COMP_WORDS[@]}" | \
		       (while read -d ' ' i; do
			   [ "$i" == "" ] && continue
			   # flatten array with spaces on either side,
			   # otherwise we cannot grep on word
			   # boundaries of first and last word
			   COMPREPLY=" ${COMPREPLY[@]} "
			   # remove word from list of completions
			   COMPREPLY=( ${COMPREPLY/ $i / } )
			done
		       echo "${COMPREPLY[@]}")
		  ) )
	return 0
}
[ $UNAME = Linux ] && complete -F _route route

# jar(1) completion
#
have jar &&
_jar()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD = 1 ]; then
		COMPREPLY=( $( compgen -W 'c t x u' -- $cur ) )
		return 0
	fi

	case "${COMP_WORDS[1]}" in
		*c*f)
			_filedir
			;;
		*f)
			_filedir '?([ejw]ar|zip|[EJW]AR|ZIP)'
			;;
		*)
			_filedir
			;;
	esac
} &&
complete -F _jar $filenames jar

# Linux iptables(8) completion
#
have iptables &&
_iptables()
{
	local cur prev table chain

	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	chain='s/^Chain \([^ ]\+\).*$/\1/p'

	if [[ $COMP_LINE == *-t\ *filter* ]]; then
		table="-t filter"
	elif [[ $COMP_LINE == *-t\ *nat* ]]; then
		table="-t nat"
	elif [[ $COMP_LINE == *-t\ *mangle* ]]; then
		table="-t mangle"
	fi

	_split_longopt

	case "$prev" in
	-*[AIDRPFXLZ])
		COMPREPLY=( $( compgen -W '`iptables $table -nL | \
			    sed -ne "s/^Chain \([^ ]\+\).*$/\1/p"`' -- $cur ) )
		;;
	-*t)
		COMPREPLY=( $( compgen -W 'nat filter mangle' -- $cur ) )
		;;
	-j)
		if [ "$table" = "-t filter" -o "$table" = "" ]; then
		    COMPREPLY=( $( compgen -W 'ACCEPT DROP LOG ULOG REJECT \
		    `iptables $table -nL | sed -ne "$chain" \
		    -e "s/INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING//"`' -- \
		    $cur ) )
		elif [ "$table" = "-t nat" ]; then
		    COMPREPLY=( $( compgen -W 'ACCEPT DROP LOG ULOG REJECT \
		    MIRROR SNAT DNAT MASQUERADE `iptables $table -nL | \
		    sed -ne "$chain" -e "s/OUTPUT|PREROUTING|POSTROUTING//"`' \
		    -- $cur ) )
		elif [ "$table" = "-t mangle" ]; then
		    COMPREPLY=( $( compgen -W 'ACCEPT DROP LOG ULOG REJECT \
		    MARK TOS `iptables $table -nL | sed -ne "$chain" \
		    -e "s/INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING//"`' -- \
		    $cur ) )
		fi
		;;
	*)
		if [[ "$cur" == -* ]]; then
		    COMPREPLY=( $( compgen -W '-i -o -s -d -p -f -m --append \
		    --delete --insert --replace --list --flush --zero --new \
		    --delete-chain --policy --rename-chain --proto --source \
		    --destination --in-interface --jump --match --numeric \
		    --out-interface --table --verbose --line-numbers --exact \
		    --fragment --modprobe --set-counters --version' -- "$cur") )
		fi
		;;
	esac

} &&
complete -F _iptables iptables

# tcpdump(8) completion
#
have tcpdump &&
_tcpdump()
{
	local cur prev

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

	case "$prev" in
		-@(r|w|F))
			_filedir
			return 0
			;;
		-i)
			_available_interfaces -a
			return 0
			;;
	esac


	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '-a -d -e -f -l -n -N -O -p \
			-q -R -S -t -u -v -x -C -F -i -m -r -s -T -w \
			-E' -- $cur ) )
	fi

} &&
complete -F _tcpdump tcpdump

# autorpm(8) completion
#
have autorpm &&
_autorpm()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( compgen -W '--notty --debug --help --version \
				   auto add fullinfo info help install list \
				   remove set' -- $cur ) )

} &&
complete -F _autorpm autorpm

# This meta-cd function observes the CDPATH variable, so that cd additionally
# completes on directories under those specified in CDPATH.
#
_cd()
{
	local IFS=$'\t\n' cur=`_get_cword` i j k

	# try to allow variable completion
	if [[ "$cur" == ?(\\)\$* ]]; then
		COMPREPLY=( $( compgen -v -P '$' -- "${cur#?(\\)$}" ) )
		return 0
	fi

	# Enable -o filenames option, see Debian bug #272660
	compgen -f /non-existing-dir/ >/dev/null

	# Use standard dir completion if no CDPATH or parameter starts with /,
	# ./ or ../
	if [ -z "${CDPATH:-}" ] || [[ "$cur" == ?(.)?(.)/* ]]; then
		_filedir -d
		return 0
	fi

	local -r mark_dirs=$(_rl_enabled mark-directories && echo y)
	local -r mark_symdirs=$(_rl_enabled mark-symlinked-directories && echo y)

	# we have a CDPATH, so loop on its contents
	for i in ${CDPATH//:/$'\t'}; do
		# create an array of matched subdirs
		k="${#COMPREPLY[@]}"
		for j in $( compgen -d $i/$cur ); do
			if [[ ( $mark_symdirs && -h $j || $mark_dirs && ! -h $j ) && ! -d ${j#$i/} ]]; then
				j="${j}/"
			fi
			COMPREPLY[k++]=${j#$i/}
		done
	done

	_filedir -d

	if [[ ${#COMPREPLY[@]} -eq 1 ]]; then
	    i=${COMPREPLY[0]}
	    if [ "$i" == "$cur" ] && [[ $i != "*/" ]]; then
		COMPREPLY[0]="${i}/"
	    fi
	fi

	return 0
}
if shopt -q cdable_vars; then
    complete -v -F _cd $nospace cd
else
    complete -F _cd $nospace cd
fi

# a wrapper method for the next one, when the offset is unknown
_command()
{
	local offset i

	# find actual offset, as position of the first non-option
	offset=1
	for (( i=1; i <= COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" != -* ]]; then
			offset=$i
			break
		fi
	done
	_command_offset $offset
}

# A meta-command completion function for commands like sudo(8), which need to
# first complete on a command, then complete according to that command's own
# completion definition - currently not quite foolproof (e.g. mount and umount
# don't work properly), but still quite useful.
#
_command_offset()
{
	local cur func cline cspec noglob cmd i char_offset word_offset \
	      _COMMAND_FUNC _COMMAND_FUNC_ARGS

	word_offset=$1

	# rewrite current completion context before invoking
	# actual command completion

	# find new first word position, then
	# rewrite COMP_LINE and adjust COMP_POINT
	local first_word=${COMP_WORDS[$word_offset]}
	for (( i=0; i <= ${#COMP_LINE}; i++ )); do
		if [[ "${COMP_LINE:$i:${#first_word}}" == "$first_word" ]]; then
			char_offset=$i
			break
		fi
	done
	COMP_LINE=${COMP_LINE:$char_offset}
	COMP_POINT=$(( COMP_POINT - $char_offset ))

	# shift COMP_WORDS elements and adjust COMP_CWORD
	for (( i=0; i <= COMP_CWORD - $word_offset; i++ )); do
		COMP_WORDS[i]=${COMP_WORDS[i+$word_offset]}
	done
	for (( i; i <= COMP_CWORD; i++ )); do
		unset COMP_WORDS[i];
	done
	COMP_CWORD=$(( $COMP_CWORD - $word_offset ))

	COMPREPLY=()
	cur=`_get_cword`

	if [[ $COMP_CWORD -eq 0 ]]; then
		COMPREPLY=( $( compgen -c -- $cur ) )
	else
		cmd=${COMP_WORDS[0]}
		if complete -p $cmd &>/dev/null; then
		cspec=$( complete -p $cmd )
		if [ "${cspec#* -F }" != "$cspec" ]; then
			# complete -F <function>

			# get function name
			func=${cspec#*-F }
			func=${func%% *}
			
			if [[ ${#COMP_WORDS[@]} -ge 2 ]]; then
				$func $cmd "${COMP_WORDS[${#COMP_WORDS[@]}-1]}"	"${COMP_WORDS[${#COMP_WORDS[@]}-2]}"
			else
				$func $cmd "${COMP_WORDS[${#COMP_WORDS[@]}-1]}"
			fi

			# remove any \: generated by a command that doesn't
			# default to filenames or dirnames (e.g. sudo chown)
			# FIXME: I'm pretty sure this does not work!
			if [ "${cspec#*-o }" != "$cspec" ]; then
				cspec=${cspec#*-o }
				cspec=${cspec%% *}
				if [[ "$cspec" != @(dir|file)names ]]; then
					COMPREPLY=("${COMPREPLY[@]//\\\\:/:}")
				fi
			fi
		elif [ -n "$cspec" ]; then
			cspec=${cspec#complete};
			cspec=${cspec%%$cmd};
			COMPREPLY=( $( eval compgen "$cspec" -- "$cur" ) );
		fi
		fi
	fi

	[ ${#COMPREPLY[@]} -eq 0 ] && _filedir
}
complete -F _command $filenames nohup exec nice eval time ltrace then \
	else do vsound command xargs tsocks

_root_command()
{
	PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin _command $1 $2 $3
}
complete -F _root_command $filenames sudo fakeroot really gksudo gksu kdesudo

_longopt()
{
	local cur prev

	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	if _split_longopt; then
		case "$prev" in
			*[Dd][Ii][Rr]*)
				_filedir -d
				;;
			*[Ff][Ii][Ll][Ee]*)
				_filedir
				;;
		esac
		return 0
	fi

	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W "$( $1 --help 2>&1 | sed -e '/--/!d' \
				-e 's/.*\(--[-A-Za-z0-9]\+\).*/\1/' |sort -u )"\
				-- $cur ) )
	elif [[ "$1" == rmdir ]]; then
		_filedir -d
	else
		_filedir
	fi
}
# makeinfo and texi2dvi are defined elsewhere.
for i in a2ps autoconf automake bc gprof ld nm objcopy objdump readelf strip \
	 bison diff patch enscript cp df dir du ln ls mkfifo mknod mv rm \
	 touch vdir awk gperf grep grub indent less m4 sed shar date \
	 tee who texindex cat csplit cut expand fmt fold head \
	 md5sum nl od paste pr ptx sha1sum sort split tac tail tr unexpand \
	 uniq wc ldd bash id irb mkdir rmdir; do
  have $i && complete -F _longopt $filenames $i
done

# These commands use filenames, so '-o filenames' is not needed.
for i in env netstat seq uname units wget; do
  have $i && complete -F _longopt $default $i
done
unset i

# gcc(1) completion
#
# The only unusual feature is that we don't parse "gcc --help -v" output
# directly, because that would include the options of all the other backend
# tools (linker, assembler, preprocessor, etc) without any indication that
# you cannot feed such options to the gcc driver directly.  (For example, the
# linker takes a -z option, but you must type -Wl,-z for gcc.)  Instead, we
# ask the driver ("g++") for the name of the compiler ("cc1"), and parse the
# --help output of the compiler.
#
have gcc &&
_gcc()
{
	local cur cc backend

	COMPREPLY=()
	cur=`_get_cword`

	_expand || return 0

	case "$1" in
	gcj)
		backend=jc1
		;;
	gpc)
		backend=gpc1
		;;
	*77)
		backend=f771
		;;
	*)
		backend=cc1	# (near-)universal backend
		;;
	esac

	if [[ "$cur" == -* ]]; then
		cc=$( $1 -print-prog-name=$backend )
		# sink stderr:
		# for C/C++/ObjectiveC it's useless
		# for FORTRAN/Java it's an error
		COMPREPLY=( $( compgen -W "$( $cc --help 2>/dev/null | \
			       tr '\t' ' ' | \
			       sed -e '/^  *-/!d' -e 's/ *-\([^ ]*\).*/-\1/' | \
			       sort -u )" -- $cur ) )
	else
		_filedir
	fi
} &&
complete $filenames -F _gcc gcc g++ c++ g77 gcj gpc
[ $USERLAND = GNU -o $UNAME = Cygwin ] && \
[ -n "${have:-}" ] && complete $filenames -F _gcc cc

# Linux cardctl(8) completion
#
have cardctl &&
_cardctl()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD -eq 1 ]; then
		COMPREPLY=( $( compgen -W 'status config ident suspend \
					   resume reset eject insert scheme' \
			       -- $cur ) )
	fi
} &&
complete -F _cardctl cardctl

# This function is required by _dpkg() and _dpkg-reconfigure()
#
# TODO: Ubuntu (and Debian) folks removed the "have grep-status" part. In my Debian I got it,
#       and I believe it's ok if we leave it like it is now. Was that removed because
#       of Ubuntu's (and Debian's? :() inner weirdness? :) -- David (hanska-guest)
have dpkg && {
#have grep-status && {
#_comp_dpkg_installed_packages()
#{
#	grep-status -P -e "^$1" -a -FStatus 'install ok installed' -n -s Package
#}
#} || {
_comp_dpkg_installed_packages()
{
	grep -A 1 "Package: $1" /var/lib/dpkg/status | \
		grep -B 1 -Ee "ok installed|half-installed|unpacked| \
					half-configured|config-files" \
				  -Ee "^Essential: yes" | \
		grep "Package: $1" | cut -d\  -f2
}
#}

# Debian dpkg(8) completion
#
_dpkg()
{
	local cur prev i

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

	_expand || return 0

	# find the last option flag
	if [[ $cur != -* ]]; then
		while [[ $prev != -* && $i != 1 ]]; do
			i=$((i-1))
			prev=${COMP_WORDS[i-1]}
		done
	fi

	case "$prev" in
	-@(c|i|A|I|f|e|x|X|-@(install|unpack|record-avail|contents|info|fsys-tarfile|field|control|extract)))
		_filedir '?(u)deb'
		return 0
		;;
	-@(b|-build))
		_filedir -d
		return 0
		;;
   	-@(s|p|l|-@(status|print-avail|list)))
		COMPREPLY=( $( apt-cache pkgnames $cur 2>/dev/null ) )
		return 0
		;;
	-@(S|-search))
		_filedir
		return 0
		;;
	-@(r|L|P|-@(remove|purge|listfiles)))
		COMPREPLY=( $( _comp_dpkg_installed_packages $cur ) )
		return 0
		;;
	*)

	COMPREPLY=( $( compgen -W '-i --install --unpack -A --record-avail \
			--configure -r --remove -P --purge --get-selections \
			--set-selections --update-avail --merge-avail \
			--clear-avail  --command-fd --forget-old-unavail -s \
			--status -p --print-avail -L --listfiles -l --list \
			-S --search -C --audit --print-architecture \
			--print-gnu-build-architecture \
			--print-installation-architecture \
			--compare-versions --help --version --force-help \
			--force-all --force-auto-select --force-downgrade \
			--force-configure-any --force-hold --force-bad-path \
			--force-not-root --force-overwrite \
			--force-overwrite-diverted --force-bad-verify \
			--force-depends-version --force-depends \
			--force-confnew --force-confold --force-confdef \
			--force-confmiss --force-conflicts --force-architecture\
			--force-overwrite-dir --force-remove-reinstreq \
			--force-remove-essential -Dh \
			--debug=help --licence --admindir= --root= --instdir= \
			-O --selected-only -E --skip-same-version \
			-G --refuse-downgrade -B --auto-deconfigure \
			--no-debsig --no-act -D --debug= --status-fd \
			-b --build -I --info -f --field -c --contents \
			-x --extract -X --vextract --fsys-tarfile -e --control \
			--ignore-depends= --abort-after' -- $cur ) )
		;;
	esac


}
complete -F _dpkg $filenames dpkg dpkg-deb
}

# Debian GNU dpkg-reconfigure(8) completion
#
have dpkg-reconfigure &&
_dpkg_reconfigure()
{
	local cur prev opt

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


	case "$prev" in
	    -@(f|-frontend))
		opt=( $( echo /usr/share/perl5/Debconf/FrontEnd/* ) )
		opt=( ${opt[@]##*/} )
		opt=( ${opt[@]%.pm} )
		COMPREPLY=( $( compgen -W '${opt[@]}' -- $cur ) )
		return 0
		;;
	    -@(p|-priority))
  		COMPREPLY=( $( compgen -W 'low medium high critical' -- $cur ) )
		return 0
		;;
	esac

	if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W '-f --frontend -p --priority -a --all \
				       -u --unseen-only -h --help -s --showold \
				       --force --terse' -- $cur ) )
	else
	    COMPREPLY=( $( _comp_dpkg_installed_packages $cur ) )
	fi
} &&
complete -F _dpkg_reconfigure $default dpkg-reconfigure

# Debian dpkg-source completion
#
have dpkg-source &&
_dpkg_source()
{
	local cur prev options work i action packopts unpackopts

	packopts="-c -l -F -V -T -D -U -W -E -sa -i -I -sk -sp -su -sr -ss -sn -sA -sK -sP -sU -sR"
	unpackopts="-sp -sn -su"
	options=`echo "-x -b $packopts $unpackopts" | xargs echo | sort -u | xargs echo`

	COMPREPLY=()
	if [ "$1" != "dpkg-source" ]; then
		return 1
	fi
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	action="options"
	for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
		if [[ ${COMP_WORDS[$i]} == "-x" ]]; then
			action=unpack
		elif [[ ${COMP_WORDS[$i]} == "-b" ]]; then
			action=pack
		elif [[ ${COMP_WORDS[$i]} == "-h" ]]; then
			action=help
		fi
	done
	# if currently seeing a complete option, return just itself.
	for i in $options; do
		if [ "$cur" = "$i" ]; then
			COMPREPLY=( "$cur" )
			return 0
		fi
	done
	case "$action" in
		"unpack")
			if [ "$cur" = "-" -o "$cur" = "-s" ]; then
				COMPREPLY=( $unpackopts )
				return 0
			fi
			case "$prev" in
				"-x")
					COMPREPLY=( $( compgen -d -- "$cur" ) \
						    $( compgen -f -X '!*.dsc' -- "$cur" ) )
					return 0
					;;
				*)
					COMPREPLY=( $unpackopts $(compgen -d -f -- "$cur" ) )
					return 0
					;;
			esac
			return 0
			;;
		"pack")
			if [ "$cur" = "-" ]; then
				COMPREPLY=( $packopts )
				return 0
			fi
			if [ "$cur" = "-s" ]; then
				COMPREPLY=( "-sa" "-sk" "-sp" "-su" "-sr" "-ss" "-sn" \
			    		"-sA" "-sK" "-sP" "-sU" "-sR" )
				return 0
			fi
			case "$prev" in
				"-b")
					COMPREPLY=( $( compgen -d -- "$cur" ) )
					return 0
					;;
				"-c"|"-l"|"-T"|"-i"|"-I")
					# -c: get controlfile
					# -l: get per-version info from this file
					# -T: read variables here, not debian/substvars
					# -i: <regexp> filter out files to ignore diffs of.
					# -I: filter out files when building tarballs.
					# return directory names and file names
					COMPREPLY=( $( compgen -d -f ) )
					return 0
					;;
				"-F")
					# -F: force change log format
					COMPREPLY=( $( ( cd /usr/lib/dpkg/parsechangelog; compgen -f "$cur" ) ) )
					return 0
					;;
				"-V"|"-D")
					# -V: set a substitution variable
					# we don't know anything about possible variables or values
					# so we don't try to suggest any completion.
					COMPREPLY=()
					return 0
					;;
				"-D")
					# -D: override or add a .dsc field and value
					# if $cur doesn't contain a = yet, suggest variable names
					if echo -- "$cur" | grep -q "="; then
						# $cur contains a "="
						COMPREPLY=()
						return 0
					else
						COMPREPLY=( Format Source Version Binary Maintainer Uploader Architecture Standards-Version Build-Depends Files )
						return 0
					fi
					;;
				"-U")
					# -U: remove a field
					# Suggest possible fieldnames
					COMPREPLY=( Format Source Version Binary Maintainer Uploader Architecture Standards-Version Build-Depends Files )
					return 0
					;;
				*)
					COMPREPLY=( $packopts )
					return 0
					;;
			esac
			return 0
			;;
		*)
			# if seeing a partial option, return possible completions.
			if [ "$cur" = "-s" ]; then
				COMPREPLY=( "-sa" "-sk" "-sp" "-su" "-sr" "-ss" "-sn" \
			    		"-sA" "-sK" "-sP" "-sU" "-sR" )
				return 0
			fi
			# else return all possible options.
			COMPREPLY=( $options )
			return 0
			;;
	esac
} &&
complete -F _dpkg_source dpkg-source

# Debian Linux dselect(8) completion.
#
have dselect &&
_dselect()
{
	local cur prev

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

	case "$prev" in
	     --admindir)
		  _filedir -d
		  return 0
		  ;;

	     -@(D|debug))
		  _filedir
		  return 0
		  ;;
	esac

	if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W '--admindir --help --version --licence \
				  --license --expert --debug' -- $cur ) )
	else
	    COMPREPLY=( $( compgen -W 'access update select install config \
				  remove quit' -- $cur ) )
	fi


	return 0
} &&
complete -F _dselect $filenames dselect

# Java completion
#

# available path elements completion
have java && {
_java_path()
{
	cur=${cur##*:}
	_filedir '@(jar|zip)'
}

# exact classpath determination
_java_find_classpath()
{
	local i

	# search first in current options
	for (( i=1; i < COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" == -@(cp|classpath) ]]; then
			classpath=${COMP_WORDS[i+1]}
			break
		fi
	done

	# default to environment
	[ -z "$classpath" ] && classpath=$CLASSPATH

	# default to current directory
	[ -z "$classpath" ] && classpath=.
}

# exact sourcepath determination
_java_find_sourcepath()
{
	local i

	# search first in current options
	for (( i=1; i < COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" == -sourcepath ]]; then
			sourcepath=${COMP_WORDS[i+1]}
			break
		fi
	done

	# default to classpath
	if [ -z "$sourcepath" ]; then
		_java_find_classpath
		sourcepath=$classpath
	fi
}

# available classes completion
_java_classes()
{
	local classpath i

	# find which classpath to use
	_java_find_classpath

	# convert package syntax to path syntax
	cur=${cur//.//}
	# parse each classpath element for classes
	for i in ${classpath//:/ }; do
		if [ -r $i ] && [[ "$i" == *.@(jar|zip) ]]; then
			if type zipinfo &>/dev/null; then
				COMPREPLY=( "${COMPREPLY[@]}" $( zipinfo -1 \
					"$i" "$cur*" 2>/dev/null | \
					grep '^[^$]*\.class$' ) )
			else
				COMPREPLY=( "${COMPREPLY[@]}" $( jar tf "$i" \
					"$cur" | grep '^[^$]*\.class$' ) )
			fi

		elif [ -d $i ]; then
			i=${i%/}
			
			# See Debian bug #496828
			COMPREPLY=( "${COMPREPLY[@]}" $( find "$i" -type f \
			-maxdepth 1 -path "$i/$cur*.class" 2>/dev/null | \
			grep -v "\\$" | sed -e "s|^$i/||" ) )
			
			# FIXME: if we have foo.class and foo/, the completion
			# returns "foo/"... how to give precedence to files
			# over directories?
		fi
	done

	# remove class extension
	COMPREPLY=( ${COMPREPLY[@]%.class} )
	# convert path syntax to package syntax
	COMPREPLY=( ${COMPREPLY[@]//\//.} )
}

# available packages completion
_java_packages()
{
	local sourcepath i

	# find which sourcepath to use
	_java_find_sourcepath

	# convert package syntax to path syntax
	cur=${cur//.//}
	# parse each sourcepath element for packages
	for i in ${sourcepath//:/ }; do
		if [ -d $i ]; then
			COMPREPLY=( "${COMPREPLY[@]}" $( command ls -F -d \
				$i/$cur* 2>/dev/null | sed -e 's|^'$i'/||' ) )
		fi
	done
	# keep only packages
	COMPREPLY=( $( echo "${COMPREPLY[@]}" | tr " " "\n" | grep "/$" ) )
	# remove packages extension
	COMPREPLY=( ${COMPREPLY[@]%/} )
	# convert path syntax to package syntax
	cur=${COMPREPLY[@]//\//.}
}

# java completion
#
_java()
{
	local cur prev i

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

	for ((i=1; i < $COMP_CWORD; i++)); do
		case ${COMP_WORDS[$i]} in
		    -cp|-classpath)
			((i++))	# skip the classpath string.
			;;
		    -*)
			# this is an option, not a class/jarfile name.
			;;
		    *)
			# once we've seen a class, just do filename completion
			_filedir
			return 0
			;;
		esac
	done

	case $prev in
		-@(cp|classpath))
			_java_path
			return 0
			;;
	esac

	if [[ "$cur" == -* ]]; then
		# relevant options completion
		COMPREPLY=( $( compgen -W '-client -hotspot -server -classic \
				-cp -classpath -D -verbose -verbose:class \
				-verbose:gc -version:jni -version \
				-showversion -? -help -X -jar \
				-ea -enableassertions -da -disableassertions \
				-esa -enablesystemassertions \
				-dsa -disablesystemassertions ' -- $cur ) )
	else
		if [[ "$prev" == -jar ]]; then
			# jar file completion
			_filedir jar
		else
			# classes completion
			_java_classes
		fi
	fi
}
complete -F _java $filenames java
}

# javadoc completion
#
have javadoc &&
_javadoc()
{
	COMPREPLY=()
	local cur prev

	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	case $prev in
		-@(overview|helpfile|stylesheetfile))
			_filedir
			return 0
			;;
		-d)
			_filedir -d
			return 0
			;;
		-@(classpath|bootclasspath|docletpath|sourcepath|extdirs))
			_java_path
			return 0
			;;
	esac

	if [[ "$cur" == -* ]]; then
		# relevant options completion
		COMPREPLY=( $( compgen -W '-overview -public -protected \
				-package -private -help -doclet -docletpath \
				-sourcepath -classpath -exclude -subpackages \
				-breakiterator -bootclasspath -source -extdirs \
				-verbose -locale -encoding -J -d -use -version \
				-author -docfilessubdirs -splitindex \
				-windowtitle -doctitle -header -footer -bottom \
				-link -linkoffline -excludedocfilessubdir \
				-group -nocomment -nodeprecated -noqualifier \
				-nosince -nodeprecatedlist -notree -noindex \
				-nohelp -nonavbar -quiet -serialwarn -tag \
				-taglet -tagletpath -charset -helpfile \
				-linksource -stylesheetfile -docencoding' -- \
				$cur ) )
	else
		# source files completion
		_filedir java
		# packages completion
		_java_packages
	fi
} &&
complete -F _javadoc $filenames javadoc

# javac completion
#
have javac &&
_javac()
{
	COMPREPLY=()
	local cur prev

	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	case $prev in
		-d)
			_filedir -d
			return 0
			;;
		-@(classpath|bootclasspath|sourcepath|extdirs))
			_java_path
			return 0
			;;
	esac

	if [[ "$cur" == -* ]]; then
		# relevant options completion
		COMPREPLY=( $( compgen -W '-g -g:none -g:lines -g:vars\
		-g:source -O -nowarn -verbose -deprecation -classpath\
		-sourcepath -bootclasspath -extdirs -d -encoding -source\
		-target -help' -- $cur ) )
	else
		# source files completion
		_filedir java
	fi
} &&
complete -F _javac $filenames javac

# PINE address-book completion
#
have pine &&
_pineaddr()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( compgen -W '$( awk "{print \$1}" ~/.addressbook 2>/dev/null)' \
			-- $cur ) )
} &&
complete -F _pineaddr $default pine

# mutt completion
#
# Mutt doesn't have an "addressbook" like Pine, but it has aliases and
# a "query" function to retrieve addresses, so that's what we use here.
have mutt || have muttng && {
_muttaddr()
{
	_muttaliases
	_muttquery

	cur=`_get_cword`
	COMPREPLY=( "${COMPREPLY[@]}" $( compgen -u -- $cur ) )

	return 0
}

_muttconffiles()
{
	local file sofar
	local -a newconffiles

	sofar=" $1 "
	shift
	while [[ "$1" ]]; do
	    newconffiles=( $(sed -rn 's|^source[[:space:]]+([^[:space:]]+).*$|\1|p' $(eval echo $1) ) )
	    for file in "${newconffiles[@]}"; do
		[[ ! "$file" ]] || [[ "${sofar/ ${file} / }" != "$sofar" ]] &&
		    continue
		sofar="$sofar $file"
		sofar=" $(eval _muttconffiles \"$sofar\" $file) "
	    done
	    shift
	done
	echo $sofar
}

_muttaliases()
{
	local cur muttrc
	local -a conffiles aliases
	cur=`_get_cword =`

	[ -f ~/.${muttcmd}/${muttcmd}rc ] && muttrc="~/.${muttcmd}/${muttcmd}rc"
	[ -f ~/.${muttcmd}rc ] && muttrc="~/.${muttcmd}rc"
	[ -z "$muttrc" ] && return 0

	conffiles=( $(eval _muttconffiles $muttrc $muttrc) )
	aliases=( $( sed -rn 's|^alias[[:space:]]+([^[:space:]]+).*$|\1|p' \
			$(eval echo "${conffiles[@]}") ) )
	COMPREPLY=( "${COMPREPLY[@]}" $( compgen -W "${aliases[*]}" -- $cur ) )

	return 0
}

_muttquery()
{
	local cur querycmd
	local -a queryresults
	cur=`_get_cword`

	querycmd="$( $muttcmd -Q query_command  | sed -r 's|^query_command=\"(.*)\"$|\1|; s|%s|'$cur'|' )"
	if [ -z "$cur" -o -z "$querycmd" ]; then
	    queryresults=()
	else
	    queryresults=( $( $querycmd | \
	      sed -nr '2,$s|^([^[:space:]]+).*|\1|p' ) )
	fi

	COMPREPLY=( "${COMPREPLY[@]}" $( compgen -W "${queryresults[*]}" \
			-- $cur ) )

	return 0
}

_muttfiledir()
{
	local cur folder spoolfile
	cur=`_get_cword`

	# This is currently not working so well. Perhaps this function should
	# just call _filedir() for the moment.
	if [[ $cur == [=+]* ]]; then
		folder="$( $muttcmd -Q folder | sed -r 's|^folder=\"(.*)\"$|\1|' )"
		: folder:=~/Mail

		# Match any file in $folder beginning with $cur
		# (minus the leading '=' sign).
		COMPREPLY=( $( compgen -f -- "$folder/${cur:1}" ) )
		COMPREPLY=( ${COMPREPLY[@]#$folder/} )
		return 0
	elif [ "$cur" == !* ]; then
		spoolfile="$( $muttcmd -Q spoolfile | sed -r 's|^spoolfile=\"(.*)\"$|\1|' )"
		[ ! -z "$spoolfile" ] && eval cur="${cur/^!/$spoolfile}";
	fi
	_filedir

	return 0
}

_mutt()
{
	local cur prev
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	COMPREPLY=()

	[ ${COMP_WORDS[0]} == muttng ] && muttcmd="muttng" || muttcmd="mutt"

	case "$cur" in
	-*)
		COMPREPLY=( $( compgen -W '-A -a -b -c -e -f -F -H -i -m -n \
					    -p -Q -R -s -v -x -y -z -Z -h' \
					    -- $cur ) )
		return 0
		;;
	*)
	    case "$prev" in
	    -@(a|f|F|H|i))
		    _muttfiledir
		    return 0
		    ;;
	    -A)
		    _muttaliases
		    return 0
		    ;;
	    -@(e|m|Q|s|h|p|R|v|y|z|Z))
		    return 0
		    ;;
	    *)
		    _muttaddr
		    return 0
		    ;;
	    esac
	    ;;
	esac

}
complete -F _mutt $default $filenames mutt muttng
}

_configure_func()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	# if $COMP_CONFIGURE_HINTS is not null, then completions of the form
	# --option=SETTING will include 'SETTING' as a contextual hint
	[[ "$cur" != -* ]] && return 0

	if [ -n "$COMP_CONFIGURE_HINTS" ]; then
		COMPREPLY=( $( $1 --help 2>&1 | awk '/^  --[A-Za-z]/ { print $1; if ($2 ~ /--[A-Za-z]/) print $2 }' | sed -e 's/[[,].*//g' | grep ^$cur ) )
	else
		COMPREPLY=( $( $1 --help 2>&1 | awk '/^  --[A-Za-z]/ { print $1; if ($2 ~ /--[A-Za-z]/) print $2 }' | sed -e 's/[[,=].*//g' | grep ^$cur ) )
	fi
}
complete -F _configure_func $default configure

# Debian reportbug(1) completion
#
have reportbug &&
_reportbug()
{
	local cur prev

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

	case "$prev" in
	    -f|--filename|-i|--include|--mta|-o|--output)
		_filedir
		return 0
		;;
	    -B|--bts)
		COMPREPLY=( $( compgen -W "debian guug kde mandrake help" -- \
			       $cur ))
		return 0
		;;
	    -e|--editor|--mua)
		COMP_WORDS=(COMP_WORDS[0] $cur)
		COMP_CWORD=1
		_command
		return 0
		;;
	    --mode)
		COMPREPLY=( $( compgen -W "novice standard expert" -- $cur ) )
		return 0
		;;
	    -S|--severity)
		COMPREPLY=( $( compgen -W "grave serious important normal \
					   minor wishlist" -- $cur ) )
		return 0
		;;
	    -u|--ui|--interface)
		COMPREPLY=( $( compgen -W "newt text gnome" -- $cur ) )
		return 0
		;;
	    -t|--type)
		COMPREPLY=( $( compgen -W "gnats debbugs" -- $cur ) )
		return 0
		;;
	    -T|--tags)
		COMPREPLY=( $( compgen -W "none \
					   woody potato sarge sarge-ignore etch etch-ignore \
					   lenny lenny-ignore sid experimental confirmed \
					   d-i fixed fixed-in-experimental fixed-upstream \
					   help l10n moreinfo patch pending security \
					   unreproducible upstream wontfix ipv6 lfs" -- $cur ))
		return 0
		;;
	    *)
		;;
	esac

	COMPREPLY=($( compgen -W '-h --help -v --version -a --af -b \
			--no-query-bts --query-bts -B --bts -c --configure \
			--no-config-files --check-available -d --debug \
			--no-check-available -e --editor --email -f \
			--filename -g --gnupg -H --header -i --include -j \
			--justification -l --ldap --no-ldap -L --list-cc -m \
			--maintonly --mode --mua --mta --mutt -n --mh --nmh \
			-o --output -p --print -P --pgp --proxy --http_proxy\
			-q --quiet -Q --query-only --realname --report-quiet \
			--reply-to --replyto -s --subject -S --severity \
			--smtphost -t --type -T --tags --template -V -x \
			--no-cc --package-version -z --no-compress \
			--ui --interface -u \
			wnpp boot-floppies kernel bugs.debian.org \
			cdimage.debian.org general installation-reports \
			listarchives lists.debian.org mirrors nm.debian.org \
			press project qa.debian.org release-notes \
			security.debian.org tech-ctte upgrade-reports \
			www.debian.org' -- $cur ) \
	    		$( apt-cache pkgnames -- $cur 2> /dev/null) )
	_filedir
	return 0
} &&
complete -F _reportbug $filenames reportbug

# Debian querybts(1) completion
#
have querybts &&
_querybts()
{
	local cur prev

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

	case "$prev" in
	    -B|--bts)
		COMPREPLY=( $( compgen -W "debian guug kde mandrake help" -- \
			       $cur ))
		return 0
		;;
	    -u|--ui|--interface)
		COMPREPLY=($( compgen -W "newt text gnome" -- $cur ))
		return 0
		;;
	    *)
		;;
	esac

	COMPREPLY=($( compgen -W '-h --help -v --version -A --archive \
			-B --bts -l --ldap --no-ldap --proxy= --http_proxy= \
			-s --source -w --web -u --ui --interface \
			wnpp boot-floppies kernel bugs.debian.org \
			cdimage.debian.org general installation-reports \
			listarchives lists.debian.org mirrors nm.debian.org \
			press project qa.debian.org release-notes \
			security.debian.org tech-ctte upgrade-reports \
			www.debian.org' -- $cur ) \
	    		$( apt-cache pkgnames -- $cur 2> /dev/null) )
} &&
complete -F _querybts $filenames querybts

# update-alternatives completion
#
have update-alternatives && {
_installed_alternatives()
{
	local admindir
	# find the admin dir
	for i in alternatives dpkg/alternatives rpm/alternatives; do
		[ -d /var/lib/$i ] && admindir=/var/lib/$i && break
	done
	for (( i=1; i < COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" == --admindir ]]; then
			admindir=${COMP_WORDS[i+1]}
			break
		fi
	done
	COMPREPLY=( $( compgen -W '$( command ls $admindir )' -- $cur ) )
}

_update_alternatives()
{
	local cur prev mode args i

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

	case "$prev" in
	--@(altdir|admindir))
		_filedir -d
		return 0
		;;
	--@(help|version))
		return 0
		;;
	esac

	# find which mode to use and how many real args used so far
	for (( i=1; i < COMP_CWORD; i++ )); do
		if [[ "${COMP_WORDS[i]}" == --@(install|remove|auto|display|config|remove-all) ]]; then
			mode=${COMP_WORDS[i]}
			args=$(($COMP_CWORD - i))
			break
		fi
	done

	case $mode in
	--install)
		case $args in
		1)
			_filedir
			;;
		2)
			_installed_alternatives
			;;
		3)
			_filedir
			;;
		esac
		;;
	--remove)
		case $args in
		1)
			_installed_alternatives
			;;
		2)
			_filedir
			;;
		esac
		;;
	--auto)
		_installed_alternatives
		;;
	--remove-all)
		_installed_alternatives
		;;
	--display)
		_installed_alternatives
		;;
	--config)
		_installed_alternatives
		;;
	*)
		COMPREPLY=( $( compgen -W '--verbose --quiet --help --version \
			       --altdir --admindir' -- $cur ) \
			    $( compgen -W '--install --remove --auto --display \
			       --config' -- $cur ) )
	esac
}
complete -F _update_alternatives update-alternatives alternatives
}

# Python completion
#
have python &&
_python()
{
	local prev cur

	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]##*/}

	case "$prev" in
	-Q)
		COMPREPLY=( $( compgen -W "old new warn warnall" -- $cur ) )
		return 0
		;;
	-W)
		COMPREPLY=( $( compgen -W "ignore default all module once error" -- $cur ) )
		return 0
		;;
	-c)
		_filedir '@(py|pyc|pyo)'
		return 0
		;;
	!(python|-?))
		[[ ${COMP_WORDS[COMP_CWORD-2]} != -@(Q|W) ]] && _filedir
		;;
	esac


	# if '-c' is already given, complete all kind of files.
	for (( i=0; i < ${#COMP_WORDS[@]}-1; i++ )); do
		if [[ ${COMP_WORDS[i]} == -c ]]; then
			_filedir
		fi
	done


	if [[ "$cur" != -* ]]; then
		_filedir '@(py|pyc|pyo)'
	else
		COMPREPLY=( $( compgen -W "- -d -E -h -i -O -Q -S -t -u \
					   -U -v -V -W -x -c" -- $cur ) )
	fi



	return 0
} &&
complete -F _python $filenames python

# Perl completion
#
have perl &&
{
_perlmodules()
{
    COMPREPLY=( $( compgen -P "$prefix" -W "$( perl -e 'sub mods { my ($base,$dir)=@_; return if  $base !~ /^\Q$ENV{cur}/; chdir($dir) or return; for (glob(q[*.pm])) {s/\.pm$//; print qq[$base$_\n]}; mods(/^(?:[.\d]+|$Config{archname}-$Config{osname}|auto)$/ ? undef : qq[${base}${_}\\\\:\\\\:],qq[$dir/$_]) for grep {-d} glob(q[*]); } mods(undef,$_) for @INC;' )" -- $cur ) )
}

_perl()
{
    local cur prev prefix temp
    local optPrefix optSuffix

    COMPREPLY=()
    cur=`_get_cword`
    prev=${COMP_WORDS[COMP_CWORD-1]}
    prefix=""

    # If option not followed by whitespace, reassign prev and cur
    if [[ "$cur" == -?* ]]; then
	temp=$cur
	prev=${temp:0:2}
	cur=${temp:2}
	optPrefix=-P$prev
	optSuffix=-S/
	prefix=$prev
    fi

    # only handle module completion for now
    case "$prev" in
    -I|-x)
    	local IFS=$'\t\n'
    	COMPREPLY=( $( compgen -d $optPrefix $optSuffix -- "$cur" ) )
    	return 0
    	;;
	-m|-M)
	    _perlmodules
	    return 0
	    ;;
    esac

    if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W '-C -s -T -u -U -W -X -h -v -V -c -w -d \
		    -D -p -n -a -F -l -0 -I -m -M -P -S -x -i -e ' -- $cur ) )
    else
	_filedir
    fi
}
complete -F _perl $nospace $filenames perl

_perldoc()
{
    local cur prev prefix temp

    COMPREPLY=()
    cur=`_get_cword`
    prev=${COMP_WORDS[COMP_CWORD-1]}
    prefix=""

    # completing an option (may or may not be separated by a space)
    if [[ "$cur" == -?* ]]; then
	temp=$cur
	prev=${temp:0:2}
	cur=${temp:2}
	prefix=$prev
    fi

    # complete builtin perl functions
    case $prev in
	-f)
	    COMPREPLY=( $( compgen -W 'chomp chop chr crypt hex index lc \
	    lcfirst length oct ord pack q qq reverse rindex sprintf \
	    substr tr uc ucfirst y m pos quotemeta s split study qr abs \
	    atan2 cos exp hex int log oct rand sin sqrt srand pop push \
	    shift splice unshift grep join map qw reverse sort unpack \
	    delete each exists keys values binmode close closedir \
	    dbmclose dbmopen die eof fileno flock format getc print \
	    printf read readdir rewinddir seek seekdir select syscall \
	    sysread sysseek syswrite tell telldir truncate warn write \
	    pack read syscall sysread syswrite unpack vec -X chdir chmod \
	    chown chroot fcntl glob ioctl link lstat mkdir open opendir \
	    readlink rename rmdir stat symlink umask unlink utime caller \
	    continue do dump eval exit goto last next redo return \
	    sub wantarray caller import local my our package use defined \
	    formline reset scalar undef \
	    alarm exec fork getpgrp getppid getpriority kill pipe qx \
	    setpgrp setpriority sleep system times wait waitpid \
	    import no package require use bless dbmclose dbmopen package \
	    ref tie tied untie use accept bind connect getpeername \
	    getsockname getsockopt listen recv send setsockopt shutdown \
	    socket socketpair msgctl msgget msgrcv msgsnd semctl semget \
	    semop shmctl shmget shmread shmwrite endgrent endhostent \
	    endnetent endpwent getgrent getgrgid getgrnam getlogin \
	    getpwent getpwnam getpwuid setgrent setpwent endprotoent \
	    endservent gethostbyaddr gethostbyname gethostent \
	    getnetbyaddr getnetbyname getnetent getprotobyname \
	    getprotobynumber getprotoent getservbyname getservbyport \
	    getservent sethostent setnetent setprotoent setservent \
	    gmtime localtime time times' -- $cur ) )
	    return 0
	    ;;
    esac

    if [[ "$cur" == -* ]]; then
	    COMPREPLY=( $( compgen -W '-h -v -t -u -m -l -F -X -f -q' -- $cur ))
    else
	    # return available modules (unless it is clearly a file)
	    if [[ "$cur" != */* ]]; then
		    _perlmodules
		    COMPREPLY=( "${COMPREPLY[@]}" $( compgen -W '$( PAGER=/bin/cat man perl |  sed -ne "/perl.*Perl overview/,/perlwin32/p" | awk "\$NF=2 { print \$1}" | grep perl )' -- $cur ) )
	    fi
    fi
}
complete -F _perldoc $default perldoc
}

# rcs(1) completion
#
have rcs &&
_rcs()
{
	local cur prev file dir i

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

	file=${cur##*/}
	dir=${cur%/*}

	# deal with relative directory
	[ "$file" = "$dir" ] && dir=.

	COMPREPLY=( $( compgen -f "$dir/RCS/$file" ) )

	for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do
		file=${COMPREPLY[$i]##*/}
		dir=${COMPREPLY[$i]%RCS/*}
		COMPREPLY[$i]=$dir$file
	done

	COMPREPLY=( "${COMPREPLY[@]}" $( compgen -G "$dir/$file*,v" ) )

	for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do
		COMPREPLY[$i]=${COMPREPLY[$i]%,v}
	done

	# default to files if nothing returned and we're checking in.
	# otherwise, default to directories
	[ ${#COMPREPLY[@]} -eq 0 -a $1 = ci ] && _filedir || _filedir -d
} &&
complete -F _rcs $filenames ci co rlog rcs rcsdiff

# lilo(8) completion
#
have lilo && {
_lilo_labels()
{
	COMPREPLY=( $( awk -F'=' '/label/ {print $2}' \
		/etc/lilo.conf | sed -e 's/"//g' | grep "^$cur" ) )
}

_lilo()
{
	local cur prev

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

	case $prev in
		-@(C|i|m|s|S))
			_filedir
			return 0
			;;
		-r)
			_filedir -d
			return 0
			;;
		-@(I|D|R))
			# label completion
			_lilo_labels
			return 0
			;;
		-@(A|b|M|u|U))
			# device completion
			cur=${cur:=/dev/}
			_filedir
			return 0
			;;
		-T)
			# topic completion
			COMPREPLY=( $( compgen -W 'help ChRul EBDA geom geom= \
					table= video' -- $cur ) )
			return 0
			;;
	esac

	if [[ "$cur" == -* ]]; then
		# relevant options completion
		COMPREPLY=( $( compgen -W '-A -b -c -C -d -f -g -i -I -l -L -m \
			-M -p -P -q -r -R -s -S -t -T -u -U -v -V -w -x -z' -- \
			$cur ) )
	fi
}
complete -F _lilo lilo
}

# links completion
#
have links &&
_links()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	case "$cur" in
	    --*)
		COMPREPLY=( $( compgen -W '--help' -- $cur ) )
		;;
	    -*)
		COMPREPLY=( $( compgen -W '-async-dns -max-connections \
				-max-connections-to-host -retries \
				-receive-timeout -unrestartable-receive-timeout\
				-format-cache-size -memory-cache-size \
				-http-proxy -ftp-proxy -download-dir \
				-assume-codepage -anonymous -dump -no-connect \
				-source -version -help' -- $cur ) )
		;;
	    *)
		if [ -r ~/.links/links.his ]; then
		    COMPREPLY=( $( compgen -W '$( < ~/.links/links.his )' \
				   -- $cur ) )
		fi
				_filedir '@(htm|html)'
				return 0
		;;
	esac

	return 0
} &&
complete -F _links $filenames links

[ $UNAME = FreeBSD ] && {
# FreeBSD package management tool completion
#
_pkg_delete()
{
	local cur pkgdir prev

	pkgdir=${PKG_DBDIR:-/var/db/pkg}/
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	[ "$prev" = "-o" -o "$prev" = "-p" -o "$prev" = "-W" ] && return 0

	COMPREPLY=( $( compgen -d $pkgdir$cur ) )
	COMPREPLY=( ${COMPREPLY[@]#$pkgdir} )

	return 0
}
complete -F _pkg_delete $dirnames pkg_delete pkg_info
have pkg_deinstall && complete -F _pkg_delete $dirnames pkg_deinstall

# FreeBSD kernel module commands
#
_kldload()
{
	local cur moddir

	moddir=/modules/
	[ -d $moddir ] || moddir=/boot/kernel/
	cur=`_get_cword`

	COMPREPLY=( $( compgen -f $moddir$cur ) )
	COMPREPLY=( ${COMPREPLY[@]#$moddir} )
	COMPREPLY=( ${COMPREPLY[@]%.ko} )

	return 0
}
complete -F _kldload $filenames kldload

_kldunload()
{
	local cur
	cur=`_get_cword`
	COMPREPLY=( $(kldstat | sed -ne "s/^.*[ \t]\+\($cur[a-z_]\+\).ko$/\1/p") )
}
complete -F _kldunload $filenames kldunload
}

# FreeBSD portupgrade completion
#
have portupgrade &&
_portupgrade()
{
	local cur pkgdir prev

	pkgdir=${PKG_DBDIR:-/var/db/pkg}/
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	[ "$prev" = "-l" -o "$prev" = "-L" -o "$prev" = "-o" ] && return 0

	COMPREPLY=( $( compgen -d $pkgdir$cur ) )
	COMPREPLY=( ${COMPREPLY[@]#$pkgdir} )
	COMPREPLY=( ${COMPREPLY[@]%-*} )

	return 0
} &&
complete -F _portupgrade $dirnames portupgrade

# FreeBSD portinstall completion
#
have portinstall &&
_portinstall()
{
	local cur portsdir prev indexfile
	local -a COMPREPLY2

	portsdir=${PORTSDIR:-/usr/ports}/
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	# First try INDEX-5
	indexfile=$portsdir/INDEX-5
	# Then INDEX if INDEX-5 does not exist or system is not FreeBSD 5.x
	[ "${OSTYPE%.*}" = "freebsd5" -a -f $indexfile ] ||
	  indexfile=$portsdir/INDEX

	[ "$prev" = "-l" -o "$prev" = "-L" -o "$prev" = "-o" ] && return 0

	COMPREPLY=( $( egrep "^$cur" < $indexfile | cut -d'|' -f1 ) )
	COMPREPLY2=( $( egrep "^[^\|]+\|$portsdir$cur" < $indexfile | \
			cut -d'|' -f2 ) )
	COMPREPLY2=( ${COMPREPLY2[@]#$portsdir} )
	COMPREPLY=( "${COMPREPLY[@]}" "${COMPREPLY2[@]}" )

	return 0
} &&
complete -F _portinstall $dirnames portinstall

# Slackware Linux removepkg completion
#
have removepkg && [ -f /etc/slackware-version ] &&
_removepkg()
{
	local packages cur

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( (cd /var/log/packages; compgen -f -- "$cur") ) )
} &&
complete -F _removepkg $filenames removepkg &&
	complete $dirnames -f -X '!*.tgz' installpkg upgradepkg explodepkg

# look(1) completion
#
have look &&
_look()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [ $COMP_CWORD = 1 ]; then
		COMPREPLY=( $( compgen -W '$(look $cur 2>/dev/null)' ) )
	fi
} &&
complete -F _look $default look

# ypcat(1) and ypmatch(1) completion
#
have ypmatch &&
_ypmatch()
{
	local cur map

	COMPREPLY=()
	cur=`_get_cword`

	[ $1 = ypcat ] && [ $COMP_CWORD -gt 1 ] && return 0
	[ $1 = ypmatch ] && [ $COMP_CWORD -gt 2 ] && return 0

	if [ $1 = ypmatch ] && [ $COMP_CWORD -eq 1 ] && \
	   [ ${#COMP_WORDS[@]} -eq 3 ]; then
		map=${COMP_WORDS[2]}
		COMPREPLY=( $( compgen -W '$( ypcat $map | \
						cut -d':' -f 1 )' -- $cur) )
	else
		[ $1 = ypmatch ] && [ $COMP_CWORD -ne 2 ] && return 0
		COMPREPLY=( $( compgen -W \
			      '$( echo $(ypcat -x | cut -d"\"" -f 2))' -- $cur))
	fi

	return 0
} &&
complete -F _ypmatch ypmatch ypcat

#xrandr(1) completion
#
have xrandr &&
_xrandr()
{
	local cur prev output modes
	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}

	case "$prev" in
		--output)
			local outputs=$(xrandr|grep 'connected'|awk '{print $1}')
			COMPREPLY=( $(compgen -W "$outputs" -- $cur))
			return 0
			;;
		--mode)
			for(( i = 1; i < COMP_CWORD; i++ )); do
				if [[ "${COMP_WORDS[i]}" == "--output" ]]; then
					output=${COMP_WORDS[i+1]}
					break
				fi
			done
			modes=$(xrandr|sed -e "1,/$output/ d" \
			-e "/connected/,$ d"|awk '{print $1}')
			COMPREPLY=( $( compgen -W "$modes" -- $cur))
			return 0
			;;
	esac

	case "$cur" in
		*)
			COMPREPLY=( $(compgen -W '-d -display -help -o \
					--orientation -q --query -s --size\
					-r --rate -v --version -x -y --screen \
					--verbose --dryrun --prop --fb --fbmm --dpi \
					--output --auto --mode --preferred --pos \
					--reflect --rotate --left-of --right-of \
					--above --below --same-as --set --off --crtc \
					--newmode --rmmode --addmode --delmode' -- $cur))
			return 0
			;;
	esac

	return 0
} &&
complete -F _xrandr xrandr

# KDE dcop completion
#
have dcop &&
_dcop()
{
	local cur compstr

	COMPREPLY=()
	cur=`_get_cword`
	if [ -z $cur ]; then
	    compstr=${COMP_WORDS[*]}
	else
	    compstr=$( command echo ${COMP_WORDS[*]} | sed "s/ $cur$//" )
	fi
	COMPREPLY=( $( compgen -W '$( command $compstr | sed s/\(.*\)// )'  -- $cur ) )
} &&
complete -F _dcop dcop

# wvdial(1) completion
#
have wvdial &&
_wvdial()
{
	local cur prev config i IFS=$'\t\n'

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

	case $prev in
		--config)
			_filedir
			return 0
			;;
	esac

	case $cur in
		-*)
			COMPREPLY=( $( compgen -W '--config --chat \
				--remotename --help --version --no-syslog' \
				-- $cur ) )
			;;
		*)
			# start with global and personal config files
		       	config="/etc/wvdial.conf"$'\t'"$HOME/.wvdialrc"
			# replace with command line config file if present
			for (( i=1; i < COMP_CWORD; i++ )); do
				if [[ "${COMP_WORDS[i]}" == "--config" ]]; then
					config=${COMP_WORDS[i+1]}
					break
				fi
			done
			# parse config files for sections and
			# remove default section
			COMPREPLY=( $( sed -ne \
				    "s|^\[Dialer \($cur.*\)\]$|\1|p" \
				    $config 2>/dev/null |grep -v '^Defaults$'))
			# escape spaces
			COMPREPLY=${COMPREPLY// /\\ }
			;;
	esac

} &&
complete -F _wvdial wvdial

# gpg(1) completion
#
have gpg &&
_gpg()
{
	local cur prev

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

	case "$prev" in
	-@(s|-sign|-clearsign|-decrypt-files|-load-extension))
		_filedir
		return 0
		;;
	--@(export|@(?(l|nr|nrl)sign|edit)-key))
		# return list of public keys
		COMPREPLY=( $( compgen -W "$( gpg --list-keys 2>/dev/null | sed -ne 's@^pub.*/\([^ ]*\).*$@\1@p;s@^.*\(<\([^>]*\)>\).*$@\2@p')" -- "$cur" ))
		return 0
		;;
	-@(r|-recipient))
		COMPREPLY=( $( compgen -W "$( gpg --list-keys 2>/dev/null | sed -ne 's@^.*<\([^>]*\)>.*$@\1@p')" -- "$cur" ))
		if [ -e ~/.gnupg/gpg.conf ]; then
			COMPREPLY=( "${COMPREPLY[@]}" $( compgen -W "$( sed -ne 's@^[ \t]*group[ \t][ \t]*\([^=]*\).*$@\1@p' ~/.gnupg/gpg.conf  )" -- "$cur") )
		fi
		return 0
		;;
	esac

	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '-s -b -e -f -c -d -a -r -u -Z -o -v\
				-q -n -N $(gpg --dump-options)' -- $cur ) )
	 fi

} &&
complete -F _gpg $default gpg

# iconv(1) completion
#
have iconv &&
_iconv()
{
	local cur prev

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

	case "$prev" in
		-@(f|t|-@(from|to)-code))
			COMPREPLY=( $( compgen -W \
			    '$( iconv --list | sed -e "s@//@@;" )' -- "$cur" ) )
			return 0
			;;
	esac


	if [[ "$cur" = -* ]]; then
		COMPREPLY=( $( compgen -W '--from-code -f --to-code -t --list
		--output -o --verbose' -- "$cur" ) )
		return 0
	fi
} &&
complete -F _iconv $default iconv

# dict(1) completion
#
{ have dict || have rdict; } && {
_dictdata()
{
	dict $host $port $1 2>/dev/null | sed -ne \
	    's/^['$'\t '']['$'\t '']*\([^'$'\t '']*\).*$/\1/p'
}

_dict()
{
	local cur prev host port db dictfile

	COMPREPLY=()
	cur=`_get_cword`
	prev=${COMP_WORDS[COMP_CWORD-1]}
	dictfile=/usr/share/dict/words

	for (( i=1; i < COMP_CWORD; i++ )); do
		case "${COMP_WORDS[i]}" in
		-@(h|--host))
			host=${COMP_WORDS[i+1]}
			[ -n "$host" ] && host="-h $host"
			i=$((++i))
			;;
		-@(p|-port))
			port=${COMP_WORDS[i+1]}
			[ -n "$port" ] && port="-p $port"
			i=$((++i))
			;;
		-@(d|-database))
			db=${COMP_WORDS[i+1]}
			[ -n "$db" ] && host="-d $db"
			i=$((++i))
			;;
		*)
			;;
		esac
	done

	if [[ "$cur" = -* ]]; then
		COMPREPLY=( $( compgen -W '-h --host -p --port -d --database \
			       -m --match -s --strategy -c --config -C \
			       --nocorrect -D --dbs -S --strats -H \
			       --serverhelp -i --info -I --serverinfo \
			       -a --noauth -u --user -k --key -V --version \
			       -L --license --help -v --verbose -r --raw \
			       -P --pager --debug --html --pipesize --client' \
			       -- "$cur" ) )
		return 0
	fi

	case "$prev" in
	-@(d|-database|i|info))
		COMPREPLY=( $( compgen -W '$( _dictdata -D )' -- "$cur" ) )
		return 0
		;;
	-@(s|-strategy))
		COMPREPLY=( $( compgen -W '$( _dictdata -S )' -- "$cur" ) )
		return 0
		;;
	*)
		;;
	esac

	[ -r $dictfile ] && \
		COMPREPLY=( $( compgen -W '$( cat $dictfile )' -- "$cur" ) )
}
complete -F _dict $default dict rdict
}

# CUPS cancel(1) completion
#
have cancel &&
_cancel()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( compgen -W "$( lpstat | cut -d' ' -f1 )" -- $cur ) )
} &&
complete -F _cancel $filenames cancel

# aspell(1) completion
#
have aspell && {
_aspell_dictionary()
{
	local datadir
	datadir=$( aspell config data-dir 2>/dev/null || echo /usr/lib/aspell )
	# First, get aliases (dicts dump does not list them)
	COMPREPLY=( $( command ls $datadir/*.alias 2>/dev/null ) )
	COMPREPLY=( ${COMPREPLY[@]%.alias} )
	COMPREPLY=( ${COMPREPLY[@]#$datadir/} )
	# Then, add the canonical dicts
	COMPREPLY=( "${COMPREPLY[@]}" $( aspell dicts 2>/dev/null ) )
	COMPREPLY=( $( compgen -W '${COMPREPLY[@]}' -- $cur ) )
}

_aspell()
{
	local cur prev split=false

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

	_split_longopt && split=true

	case "$prev" in
		-c|-p|check|--@(conf|personal|repl|per-conf))
			_filedir
			return 0
			;;
		--@(conf-dir|data-dir|dict-dir|home-dir|local-data-dir|prefix))
			_filedir -d
			return 0
			;;
		dump|create|merge)
			COMPREPLY=( $( compgen -W 'master personal repl' -- $cur ) )
			return 0
			;;
		--mode)
			COMPREPLY=( $( compgen -W 'none url email sgml tex' -- $cur ) )
			return 0
			;;
		--sug-mode)
			COMPREPLY=( $( compgen -W 'ultra fast normal bad-speller' -- $cur ) )
			return 0
			;;
		--keymapping)
			COMPREPLY=( $( compgen -W 'aspell ispell' -- $cur ) )
			return 0
			;;
		-d|--master)
			_aspell_dictionary
			return 0
			;;
	esac

	$split && return 0

	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '--conf --conf-dir --data-dir --dict-dir \
			--encoding --add-filter --rem-filter --mode -e \
			-H -t --add-extra-dicts --rem-extra-dicts \
			--home-dir -W --ignore --ignore-accents \
			--dont-ignore-accents --ignore-case --dont-ignore-case \
			--ignore-repl --dont-ignore-repl --jargon --keyboard \
			--lang --language-tag --local-data-dir -d --master \
			--module --add-module-search-order \
			--rem-module-search-order --per-conf -p --personal \
			--prefix --repl -C -B --run-together --dont-run-together \
			--run-together-limit --run-together-min --save-repl \
			--dont-save-repl --set-prefix --dont-set-prefix --size \
			--spelling --strip-accents --dont-strip-accents \
			--sug-mode --add-word-list-path --rem-word-list-path \
			-b -x --backup -b|-x --dont-backup --reverse --dont-reverse \
			--time --dont-time --keymapping --add-email-quote \
			--rem-email-quote --email-margin --add-tex-command \
			--rem-tex-command --tex-check-comments \
			--dont-tex-check-comments --add-tex-extension \
			--rem-tex-extension --add-sgml-check --rem-sgml-check \
			--add-sgml-extension --rem-sgml-extension' -- $cur ) )
	else
		COMPREPLY=( $( compgen -W '-? help -c check -a pipe -l list \
			config config soundslike filter -v version dump \
			create merge' -- $cur ) )
	fi

}
complete -F _aspell $filenames aspell
}

# info(1) completion
#
have info &&
_info()
{
	local cur infopath

	COMPREPLY=()
	cur=`_get_cword`

	_expand || return 0

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

	infopath='/usr/share/info'

	if [ "${INFOPATH: -1:1}" == ':' ]; then
		infopath=${INFOPATH}${infopath}
	elif [ ${INFOPATH:+set} ]; then
		infopath=$INFOPATH
	fi

	infopath=$infopath:
	if [ -n "$cur" ]; then
		infopath="${infopath//://$cur* }"
	else
		infopath="${infopath//:// }"
	fi

	# redirect stderr for when path doesn't exist
	COMPREPLY=( $( eval command ls "$infopath" 2>/dev/null ) )
	# weed out directory path names and paths to info pages
	COMPREPLY=( ${COMPREPLY[@]##*/?(:)} )
	# weed out info dir file
	for (( i=0 ; i < ${#COMPREPLY[@]} ; ++i )); do
		if [ "${COMPREPLY[$i]}" == 'dir' ]; then
			unset COMPREPLY[$i];
		fi;
	done
	# strip suffix from info pages
	COMPREPLY=( ${COMPREPLY[@]%.@(gz|bz2|lzma)} )
	COMPREPLY=( $( compgen -W '${COMPREPLY[@]%.*}' -- "${cur//\\\\/}" ) )

	return 0
} &&
complete -F _info $filenames info

# id(1) completion
#
have id &&
_id()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	if [[ "$cur" == -* ]]; then
		COMPREPLY=( $( compgen -W '-a -g --group -G --groups -n --name\
			-r --real -u --user --help --version' -- $cur ) )
	else
		COMPREPLY=( $( compgen -u $cur  ) )
	fi
} &&
complete -F _id id

# sysctl(8) completion
#
have sysctl &&
_sysctl()
{
	local cur

	COMPREPLY=()
	cur=`_get_cword`

	COMPREPLY=( $( compgen -W "$(sysctl -N -a 2>/dev/null)" -- $cur ) )

	return 0
} &&
complete -F _sysctl sysctl

# update-rc.d(8) completion
#
# Copyright (C) 2004 Servilio Afre Puentes <servilio@gmail.com>
#
have update-rc.d &&
_update_rc_d()
{
    local cur prev sysvdir services options valid_options

    cur=`_get_cword`
    prev=${COMP_WORDS[COMP_CWORD-1]}

    [ -d /etc/rc.d/init.d ] && sysvdir=/etc/rc.d/init.d \
	|| sysvdir=/etc/init.d

    services=( $(echo $sysvdir/!(README*|*.sh|*.dpkg*|*.rpm@(orig|new|save))) )
    services=( ${services[@]#$sysvdir/} )
    options=( -f -n )

    if [[ $COMP_CWORD -eq 1 || "$prev" == -* ]]; then
	valid_options=( $( \
	    echo "${COMP_WORDS[@]} ${options[@]}" \
	    | tr " " "\n" \
	    | sed -ne "/$( echo "${options[@]}" | sed "s/ /\\|/g" )/p" \
	    | sort | uniq -u \
	    ) )
	COMPREPLY=( $( compgen -W '${options[@]} ${services[@]}' \
	    -X '$( echo ${COMP_WORDS[@]} | tr " " "|" )' -- $cur ) )
    elif [[ "$prev" == ?($( echo ${services[@]} | tr " " "|" )) ]]; then
	COMPREPLY=( $( compgen -W 'remove defaults start stop' -- $cur ) )
    elif [[ "$prev" == defaults && "$cur" == [0-9] ]]; then
	COMPREPLY=( 0 1 2 3 4 5 6 7 8 9 )
    elif [[ "$prev" == defaults && "$cur" == [sk]?([0-9]) ]]; then
	COMPREPLY=( 0 1 2 3 4 5 6 7 8 9 )
    elif [[ "$prev" == defaults && -z "$cur" ]]; then
	COMPREPLY=( 0 1 2 3 4 5 6 7 8 9 s k )
    elif [[ "$prev" == ?(start|stop) ]]; then
	if [[ "$cur" == [0-9] || -z "$cur" ]]; then
	    COMPREPLY=( 0 1 2 3 4 5 6 7 8 9 )
	elif [[ "$cur" == [0-9][0-9] ]]; then
	    COMPREPLY=( $cur )
	else
	    COMPREPLY=()
	fi
    elif [[ "$prev" == ?([0-9][0-9]|[0-6S]) ]]; then
	if [[ -z "$cur" ]]; then
	    if [[ $prev == [0-9][0-9] ]]; then
		COMPREPLY=( 0 1 2 3 4 5 6 S )
	    else
		COMPREPLY=( 0 1 2 3 4 5 6 S . )
	    fi
	elif [[ "$cur" == [0-6S.] ]]; then
	    COMPREPLY=( $cur )
	else
	    COMPREPLY=()
	fi
    elif [[ "$prev" == "." ]]; then
	COMPREPLY=( $(compgen -W "start stop" -- $cur) )
    else
	COMPREPLY=()
    fi

    return 0
} &&
complete -F _update_rc_d update-rc.d

# invoke-rc.d(8) completion
#
# Copyright (C) 2004 Servilio Afre Puentes <servilio@gmail.com>
#
have invoke-rc.d &&
_invoke_rc_d()
{
    local cur prev sysvdir services options valid_options

    cur=`_get_cword`
    prev=${COMP_WORDS[COMP_CWORD-1]}

    [ -d /etc/rc.d/init.d ] && sysvdir=/etc/rc.d/init.d \
	|| sysvdir=/etc/init.d

    services=( $(echo $sysvdir/!(README*|*.sh|*.dpkg*|*.rpm@(orig|new|save))) )
    services=( ${services[@]#$sysvdir/} )
    options=( --help --quiet --force --try-anyway --disclose-deny --query --no-fallback )

    if [[ ($COMP_CWORD -eq 1) || ("$prev" == --* ) ]]; then
	valid_options=( $( \
	    echo ${COMP_WORDS[@]} ${options[@]} \
	    | tr " " "\n" \
	    | sed -ne "/$( echo ${options[@]} | sed "s/ /\\\\|/g" )/p" \
	    | sort | uniq -u \
	    ) )
	COMPREPLY=( $( compgen -W '${valid_options[@]} ${services[@]}' -- \
	    $cur ) )
    elif [ -x $sysvdir/$prev ]; then
	COMPREPLY=( $( compgen -W '`sed -ne "y/|/ /; \
					    s/^.*Usage:[ ]*[^ ]*[ ]*{*\([^}\"]*\).*$/\1/p" \
					    $sysvdir/$prev`' -- \
	    $cur ) )
    else
	COMPREPLY=()
    fi

    return 0
} &&
complete -F _invoke_rc_d invoke-rc.d

have rrdtool &&
_rrdtool ()
{
	cur=`_get_cword`
	COMPREPLY=( $( compgen -W 'create update updatev graph dump \
	                           restore last lastupdate first info \
	                           fetch tune resize xport' -- $cur ) )
} &&
complete -F _rrdtool rrdtool

_filedir_xspec()
{
	local IFS cur xspec

	IFS=$'\t\n'
	COMPREPLY=()
	cur=`_get_cword`

	_expand || return 0

	# get first exclusion compspec that matches this command
	xspec=$( sed -ne $'/^complete .*[ \t]'${1##*/}$'\([ \t]\|$\)/{p;q;}' \
		  $BASH_COMPLETION )
	# prune to leave nothing but the -X spec
	xspec=${xspec#*-X }
	xspec=${xspec%% *}

	local -a toks
	local tmp

	toks=( ${toks[@]-} $(
		compgen -d -- "$(quote_readline "$cur")" | {
			while read -r tmp; do
				# see long TODO comment in _filedir() --David
				echo $tmp
			done
		}
	))
	
	toks=( ${toks[@]-} $(
		eval compgen -f -X "$xspec" -- "\$(quote_readline "\$cur")" | {
			while read -r tmp; do
				[ -n $tmp ] && echo $tmp
			done
		}
	))
	
	COMPREPLY=( "${toks[@]}" )
}
list=( $( sed -ne '/^# START exclude/,/^# FINISH exclude/p' \
	  $BASH_COMPLETION | \
	# read exclusion compspecs
	(
	while read line
	do
		# ignore compspecs that are commented out
		if [ "${line#\#}" != "$line" ]; then continue; fi
		line=${line%# START exclude*}
		line=${line%# FINISH exclude*}
		line=${line##*\'}
		list=( "${list[@]}" $line )
	done
	echo "${list[@]}"
	)
     ) )
# remove previous compspecs
if [ ${#list[@]} -gt 0 ]; then
    eval complete -r ${list[@]}
    # install new compspecs
    eval complete -F _filedir_xspec $filenames "${list[@]}"
fi
unset list

# source completion directory definitions
if [ -d $BASH_COMPLETION_COMPAT_DIR -a -r $BASH_COMPLETION_COMPAT_DIR -a \
	 -x $BASH_COMPLETION_COMPAT_DIR ]; then
	for i in $BASH_COMPLETION_COMPAT_DIR/*; do
		[[ ${i##*/} != @(*~|*.bak|*.swp|\#*\#|*.dpkg*|*.rpm@(orig|new|save)) ]] &&
			[ \( -f $i -o -h $i \) -a -r $i ] && . $i		
	done
fi
if [ -d $BASH_COMPLETION_DIR -a -r $BASH_COMPLETION_DIR -a \
     $BASH_COMPLETION_DIR != $BASH_COMPLETION_COMPAT_DIR -a \
     -x $BASH_COMPLETION_DIR ]; then
	for i in $BASH_COMPLETION_DIR/*; do
		[[ ${i##*/} != @(*~|*.bak|*.swp|\#*\#|*.dpkg*|*.rpm@(orig|new|save)) ]] &&
			[ \( -f $i -o -h $i \) -a -r $i ] && . $i
	done
fi
unset i

# source user completion file
[ $BASH_COMPLETION != ~/.bash_completion -a -r ~/.bash_completion ] \
	&& . ~/.bash_completion
unset -f have
unset UNAME USERLAND default dirnames filenames have nospace bashdefault plusdirs

set $BASH_COMPLETION_ORIGINAL_V_VALUE
unset BASH_COMPLETION_ORIGINAL_V_VALUE
