#
#  Bash completion for zabbix-server
#

shopt -s extglob

_zabbix-server()
{
	local cur prev opts unique_opts nonunique_opts unique_opts_space nonunique_opts_space opt option
	local runtime_options config_supplied config_path pid_file parent_pid
	COMPREPLY=()
	_get_comp_words_by_ref -n = cur prev

	unique_opts="-h|--help|-V|--version"
	nonunique_opts="-c|-R|-f|--config|--runtime-control|--foreground"
	unique_opts_space=${unique_opts//|/ }
	nonunique_opts_space=${nonunique_opts//|/ }
	runtime_simple_options="config_cache_reload housekeeper_execute"
	runtime_loglevel_options="log_level_increase log_level_decrease"
	runtime_options="$runtime_simple_options $runtime_loglevel_options"
	runtime_processes=( alerter "configuration\ syncer" "db\ watchdog" discoverer escalator "history\ syncer" housekeeper "http\ poller" "icmp\ pinger" "ipmi\ poller" "java\ poller" poller "proxy\ poller" self-monitoring timer trapper "unreachable\ poller" "vmware\ collector" )

	opts=" $unique_opts_space $nonunique_opts_space "
	for (( i=1; i<=${#COMP_WORDS[@]-1}; ++i )) ; do
		opt=${COMP_WORDS[$i]}
		[[ $config_supplied ]] && {
			config_path=$opt
			unset config_supplied
			continue
		}
		[[ $opt =~ --*[hvVcRrf].* ]] && {
			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 / }

		[[ $option == "-c" ]] && {
			config_supplied=yes
		}

		# remove alternatives
		case $option in
			-R)                opts="${opts/ --runtime-control/}" ;;
			--runtime-control) opts="${opts/ -R/}" ;;
			-c)                opts="${opts/ --config/}" ;;
			--config)          opts="${opts/ -c/}" ;;
		esac
	done
	case "${prev}" in
		-@(c|-config))
			compopt -o default
			COMPREPLY=()
			return 0
			;;
		-@(R|-runtime-control))
			_zabbix-daemons-runtime "$cur" server
			return 0
			;;
		*)
			;;
	esac

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