#
#  Bash completion for zabbix-get
#

shopt -s extglob

_zabbix-get()
{
	local cur prev opts unique_opts nonunique_opts unique_opts_space nonunique_opts_space opt option
	local keys
	COMPREPLY=()
	_get_comp_words_by_ref -n = cur prev
	unique_opts="-h|--help|-V|--version"
	nonunique_opts="-s|-p|-I|-k|--host|--port|--source-address|--key"
	unique_opts_space=${unique_opts//|/ }
	nonunique_opts_space=${nonunique_opts//|/ }
	keys="agent.hostname agent.ping agent.version kernel.maxfiles kernel.maxproc net.dns[ net.dns.record[ \
		net.if.collisions[ net.if.discovery net.if.in[ net.if.out[ net.if.total[ net.tcp.listen[ net.tcp.port[ net.tcp.service[ \
		net.tcp.service.perf[ net.udp.listen[ proc.mem[ proc.num[ sensor[ system.boottime system.cpu.discovery system.cpu.intr \
		system.cpu.load[ system.cpu.num[ system.cpu.switches system.cpu.util[ system.hostname[ system.hw.chassis[ system.hw.cpu[ \
		system.hw.devices[ system.hw.macaddr[ system.localtime[ system.run[ system.stat[ system.sw.arch system.sw.os[ \
		system.sw.packages[ system.swap.in[ system.swap.out[ system.swap.size[ system.uname system.uptime system.users.num \
		vfs.dev.read[ vfs.dev.write[ vfs.file.cksum[ vfs.file.contents[ vfs.file.exists[ vfs.file.md5sum[ vfs.file.regexp[ \
		vfs.file.regmatch[ vfs.file.size[ vfs.file.time[ vfs.fs.discovery vfs.fs.inode[ vfs.fs.size[ vm.memory.size[ \
		web.page.get[ web.page.perf[ web.page.regexp[ eventlog[ net.if.list perf_counter[ proc_info[ service_state[ services[ wmi.get["

	opts=" $unique_opts_space $nonunique_opts_space "
	for (( i=1; i<=${#COMP_WORDS[@]-1}; ++i )) ; do
		opt=${COMP_WORDS[$i]}

		[[ $opt =~ --*[spIkhVv].* ]] && {
			option=$opt
		} || {
			continue
		}
		# if a unique option has been supplied, do not offer any other options
		[[ $option == @($unique_opts) ]] && {
			return 1
		}
		# if a non-unique option has been supplied, remove all unique options and already used options
		[[ $option == @($nonunique_opts) ]] && opts="${opts/$unique_opts_space/}"
		opts=${opts/ $option / }

		# remove alternatives
		case $option in
			-s)                opts="${opts/ --host/}" ;;
			--host)            opts="${opts/ -s/}" ;;
			-I)                opts="${opts/ --source-address/}" ;;
			--source-address)  opts="${opts/ -I/}" ;;
			-p)                opts="${opts/ --port/}" ;;
			--port)            opts="${opts/ -p/}" ;;
			-k)                opts="${opts/ --key/}" ;;
			--key)             opts="${opts/ -k/}" ;;
		esac
	done
	case "${prev}" in
		-@(s|-host))
			COMPREPLY=( $(compgen -A hostname ${cur}) )
			return 0
			;;
		-@(I|-source-address))
			COMPREPLY=( $(compgen -W "$(ip -o addr show | awk '{sub(/\/.*/,"",$4); print $4}')" -- ${cur}) )
			return 0
			;;
		-@(k|-key))
			COMPREPLY=( $(compgen -W "${keys}" -- ${cur}) )
			if [[ $COMPREPLY =~ "[" ]]; then
				compopt -o nospace
			fi
			return 0
			;;
		-@(p|-port))
			return 1
			;;
		*)
			;;
	esac

	COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
}
complete -F _zabbix-get zabbix-get
