#
#  $Id: zfs_completion,v 1.1 2006/11/07 18:44:35 dgregor Exp $
#
# Bash programmable completion scripts for Sun's ZFS
#
# This is made for use with Ian Caliban's Bash completion scripts:
#
#	http://www.caliban.org/bash/index.shtml#completion
#
# Put the contents of this file in $HOME/.bash_completion, and if you
# are already loading the above bash completions, it will be loaded
# automatically.
#
# If you want to use this on its own, put it in your $HOME/.bash_profile
# or another appropriate Bash startup script, but remove the "have zfs &&"
# part.
#
# TODO:
# - Lots... this is the first shot, and it works for pools, filesystems,
#   and snapshots.
# - I could probably improve performance quite a bit and use more Bash-isms.
#

have zfs &&
_zfs()
{
	local cur

	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"

	if echo "$cur" | grep '/' > /dev/null; then
		local parent
		local list
		local no_snapshots=""

		parent="`echo \"$cur\" | sed 's%\\\@.*$%%'`"
		if [ x"$parent" = x"$cur" ]; then
			parent="`echo \"$cur\" | sed 's%/[^/]*$%%'`"

			# If we don't have an exact match, don't show snapshots
			zfs list "$cur" > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				no_snapshots="-X *\@*"
			fi
		fi

		list=( $( compgen $no_snapshots -W '$( zfs list -r "$parent" | awk "NR != 1 { print \$1 }" )' -- $cur ) )
		COMPREPLY=( ${list[*]//@/\\@} )
	else
		COMPREPLY=( $( compgen -W '$( zpool list | awk "NR != 1 { print \$1 }" )' -- $cur ) )
	fi

	return 0
} &&
complete -o nospace -F _zfs zfs
complete -o nospace -F _zfs zpool
