#
# Bash completion for:
#
# zrep 1.7.7
# http://www.bolthole.com/solaris/zrep
# http://www.github.com/bolthole/zrep
#

#
# Install by copying this file here: /etc/bash_completion.d/zrep
#

have zrep && {

#
# Get zrep commands from help message, knowing not all are mentioned.
#

__zrep_list_commands() {
	local cmd_notmentioned="sentsync"
	zrep |
	sed -n '/Simple usage summary:/,/The above two commands/p' |
	sed -nr 's/\s*zrep ([^ ]+).*/\1/p' |
	sed 's/[()]//g;s/[|]/\n/g' |
	(echo "$cmd_notmentioned" && cat) |
	sort -u
}

__zrep_list_datasets() {
	zrep list
}

__zrep_list_master_datasets() {
	zrep list -L
}

__zrep_list_master_snapshots() {
	zrep list -s | sed -r '/^NAME\s+CREATION$/d;s/\s+.*//g'
}

__zrep_list_sent_master_snapshots() {
	zfs list -H -t snapshot -o name,zrep:master,zrep:sent |
	sed -r '/-$/d;/\t-\t/d;s/\t+.*//g'
}

__zfs_list_all_datasets() {
	zfs list -H -o name
}

__ssh_list_hosts() {
	if [ -e $HOME/.ssh/config ]; then
		sed -nr 's/[hH][oO][sS][tT]\s+(.*)/\1/p' $HOME/.ssh/config |
		sed 's/[*]//g'
	fi
}

#
# If zrep command has option flags mention them here.
#

__zrep_opts() {
	local cmd="${1}"
	case "${cmd}" in
		sync|-S) echo "-f -v -q all" ;;
		status|-s) echo "-v -a" ;;
		refresh) echo "-f -v" ;;
		list|-l) echo "-L -v -s" ;;
		expire|-e) echo "-L all" ;;
		changeconfig|-C) echo "-f -d" ;;
		failover|takeover) echo "-L" ;;
		clear) echo "-f" ;;
	esac
}

#
# Put zrep commands in one of the case elements below.
#

__zrep_complete() {
	local cur prev words cword cmd
	_init_completion || return
	cmd="${COMP_WORDS[1]}"

	if [[ ${prev##*/} = zrep ]]; then
		COMPREPLY=($(compgen -W "$(__zrep_list_commands)" -- "$cur"))
		return
	fi

	case "${cmd}" in
		version) ;;
		refresh|failover|snaponly|synconly)
			COMPREPLY=($(compgen -W "$(__zrep_list_master_datasets) $(__zrep_opts $cmd)" -- "$cur")) ;;
		sync|-S)
			COMPREPLY=($(compgen -W "$(__zrep_list_master_datasets) $(__zrep_list_sent_master_snapshots) $(__zrep_opts $cmd)" -- "$cur")) ;;
		init|-i|changeconfig|-C)
			case $COMP_CWORD in
			2)
				COMPREPLY=($(compgen -W "$(__zfs_list_all_datasets)" -- "$cur")) ;;
			3)
				COMPREPLY=($(compgen -W "$(__ssh_list_hosts)" -- "$cur"))
				_known_hosts_real -a "$cur" ;;
			4)
				COMPREPLY=($(compgen -W "${COMP_WORDS[2]}" -- "$cur")) ;;
			esac ;;
		status|-s|list|-l|expire|-e|takeover|uptodate|clear)
			COMPREPLY=($(compgen -W "$(__zrep_list_datasets) $(__zrep_opts $cmd)" -- "$cur")) ;;
		sentsync)
			COMPREPLY=($(compgen -W "$(__zrep_list_master_snapshots)" -- "$cur")) ;;
	esac
}

complete -F __zrep_complete zrep

}