#!/bin/bash completion for hapc

_hapc() {
	local cur prev cmd_name
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD-1]}"
	cmd_name="${COMP_WORDS[1]}"

	actions="list-frontends list-backends list-config-backends list-servers list-connections enable-server drain-server stop-server check-safe-to-remove reload-haproxy"

	case "${cmd_name}" in
	"list-frontends")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--verbose" -- ${cur}) )
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	"list-config-backends")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--frontend" -- ${cur}) )
			return 0
		;;
		3)
			local frontend_list=$(hapc list-frontends)
			COMPREPLY=( $(compgen -W "${frontend_list}" -- ${cur}) )
			return 0
		;;
		4)
			COMPREPLY=( $(compgen -W "--verbose" -- ${cur}) )
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	"list-backends")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--verbose" -- ${cur}) )
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	"list-servers")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--backend" -- ${cur}) )
			return 0
		;;
		3)
			local backend_list=$(hapc list-backends | tr \\n " ")
			COMPREPLY=( $(compgen -W "${backend_list}" -- ${cur}) )
			return 0
		;;
		4)
			COMPREPLY=( $(compgen -W "--details --verbose" -- ${cur}) )
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	"list-connections"|"enable-server"|"drain-server"|"stop-server"|"check-safe-to-remove")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--backend" -- ${cur}) )
			return 0
		;;
		3)
			local backend_list=$(hapc list-backends | tr \\n " ")
			COMPREPLY=( $(compgen -W "${backend_list}" -- ${cur}) )
			return 0
		;;
		4)
			COMPREPLY=( $(compgen -W "--server" -- ${cur}) )
			return 0
		;;
		5)
			local servers_list=$(hapc list-servers --backend ${COMP_WORDS[3]} | tr \\n " ")
			COMPREPLY=( $(compgen -W "${servers_list}" -- ${cur}) )
			return 0
		;;
		6)
			if [ "${cmd_name}" = "drain-server" ] ; then
				COMPREPLY=( $(compgen -W "--verbose --wait" -- ${cur}) )
			else
				COMPREPLY=( $(compgen -W "--verbose" -- ${cur}) )
			fi
			return 0
		;;
		7)
			if [ "${cmd_name}" = "drain-server" ] ; then
				COMPREPLY=( $(compgen -W "--wait" -- ${cur}) )
			fi
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	"reload-haproxy")
		case ${COMP_CWORD} in
		2)
			COMPREPLY=( $(compgen -W "--verbose" -- ${cur}) )
			return 0
		;;
		*)
			return 0
		;;
		esac
	;;
	*)
	;;
	esac

	COMPREPLY=($(compgen -W "${actions}" -- "${cur}"))
}

complete -F _hapc hapc
