# Foomuuri completion                              -*- shell-script -*-

_comp_cmd_foomuuri()
{
    local cur prev words cword was_split comp_args
    _comp_initialize -s -- "$@" || return

    local option_count=0
    for word in "${words[@]}"; do
	if [[ "${word}" == --* ]]; then
	    option_count=$((option_count+1))
	fi
    done

    case $((cword-option_count)) in
	1)
	    _comp_compgen -- -W "help start stop reload try-reload status check block list iplist set"
	    ;;
	2)
	    case ${prev} in
		list)
		    zones=$(foomuuri --quiet --quiet status | sed '/^  /!d; s/^  //; s/ .*//')
		    if [[ ${cur} =~ "-" ]]; then
			for szone in ${zones}; do
			    for dzone in ${zones}; do
				_comp_compgen -a -- -W "${szone}-${dzone}"
			    done
			done
		    else
			_comp_compgen -- -W "\"macro \" \"counter \""
			for zone in ${zones}; do
			    _comp_compgen -a -- -W "${zone}-"
			done
			compopt -o nospace
		    fi
		    ;;
		iplist)
		    _comp_compgen -- -W "list add del flush refresh"
		    ;;
		set)
		    _comp_compgen -- -W "interface"
		    ;;
	    esac
	    ;;
	3)
	    case ${prev} in
		counter)  # list
		    counters=$(foomuuri --quiet --quiet list counter | sed 's/ .*//')
		    _comp_compgen -- -W "${counters}"
		    ;;
		macro)  # list
		    macros=$(foomuuri --quiet --quiet list macro | sed '/^  /!d; s/^  //; s/ .*//')
		    _comp_compgen -- -W "${macros}"
		    ;;
		list | add | del | flush | refresh)  # iplist
		    iplists=$(foomuuri --quiet --quiet iplist list | sed 's/ .*//')
		    _comp_compgen -- -W "${iplists}"
		    ;;
		interface)  # set
		    interfaces=$(ip link show | sed '/^[0-9]\+: /!d; s/[0-9]\+: //; /lo:/d; s/:.*//')
		    _comp_compgen -- -W "${interfaces}"
		    ;;
	    esac
	    ;;
	4)
	    interfaces=$(ip link show | sed '/^[0-9]\+: /!d; s/[0-9]\+: //; /lo:/d; s/:.*//')
	    for intf in ${interfaces}; do
		if [ "${prev}" = "${intf}" ]; then
		    _comp_compgen -- -W "zone"
		fi
	    done
	    ;;
	5)
	    case ${prev} in
		zone)
		    zones=$(foomuuri --quiet --quiet status | sed '/^  /!d; s/^  //; s/ .*//')
		    _comp_compgen -- -W "${zones} -"
		    return  # "-" is not an option
		    ;;
	    esac
	    ;;
    esac

    [[ ${was_split} ]] && return

    if [[ ${cur} == -* ]]; then
        _comp_compgen_help
	[[ ${COMPREPLY-} == *= ]] && compopt -o nospace
    fi

} && complete -F _comp_cmd_foomuuri foomuuri

# ex: filetype=sh
