#compdef ipset

local offset=0
local -a args from_to hash cmds listopts

_set_types () {
	_values -S \  "Set type" \
		'ipmap[up to 65536 IP addresses]' \
		'macipmap[up to 65536 IP addresses with MAC]' \
		'portmap[up to 65536 ports]' \
		'iphash[hash of IP addresses]' \
		'nethash[hash of network addresses]' \
		'ipporthash[hash of IP address and port pairs]' \
		'ipportiphash[hash of IP address,port and IP address triples]' \
		'ipportnethash[hash of IP address,port and network address triples]' \
		'iptree[tree of IP addresses, optionally with timeout]' \
		'iptreemap[tree of IP addresses or networks]' \
		'setlist[list of sets]'
}

if [[ $words[2] = (-q|--quiet) ]]; then
	offset=1
fi

_ipsets () {
	local -a vals
	vals=( ${${(M)${(f)"$(_call_program ipsets ipset -nL)"}%Name: *}#Name: } )
	_describe -t ipsets "IP sets" vals
}
_sets () {
	_ipsets
	local -a vals
	case $words[offset+2]; in
	  -X|--destroy)
		vals=('\:all\::remove all not referenced sets')
	  ;;
	  -F|--flush)
		vals=('\:all\::flush all sets')
	  ;;
	  -L|--list|-nL|-sL|-nsL|-snL|-n|-s|-ns|-sn)
		vals=('\:all\::list all sets')
	  ;;
	  -S|--save)
		vals=('\:all\::save all sets')
	esac
	_describe -t special_values "special values" vals
}

from_to=('(--network)--from[from IP or network (with --netmask)]:IP'
	'(--network)--to[to IP or network (with --netmask)]:IP'
	'(--from --to)--network[network]:IP/mask'
)
hash=(	'--hashsize[the initial hash size (default 1024)]:hash size'
	'--probes[max number of tries to resolve clashing (default 8)]:probes'
	'--resize[ratio of increasing hash size after unsuccessful <probes> number of double-hashing]:percent'
)

case $words[offset+2]; in
  -N|--create)
	case $words[offset+4]; in
	  ipmap)
		args=(	$from_to
			'--netmask[store network addresses instead of IP addresses]:CIDR'
		)
	  ;;
	  macipmap)
		args=(	$from_to
			'--matchunset[always match IP addresses which could be stored in the set but are not]'
		)
	  ;;
	  portmap)
		args=(	'--from[from port]:port:_ports'
			'--to[to port]:port:_ports'
		)
	  ;;
	  iphash)
		args=(	$hash
			'--netmask[store network addresses instead of IP addresses]:CIDR'
		)
	  ;;
	  nethash)
		args=(	$hash )
	  ;;
	  ipporthash|ipportiphash|ipportnethash)
		args=(	$from_to $hash )
	  ;;
	  iptree)
	  	args=(	'--timeout[timeout value for the entries in seconds (default 0)]:timeout' )
	  ;;
	  iptreemap)
	  	args=(	'--gc[garbage collection inverval (default 300 seconds)]:timeout' )
	  ;;
	  setlist)
	  	args=(	'--size[size of the new setlist (default 8)]:size' )
	  ;;
	esac
  ;;
  -T|--test)
	args=(	'(-b --binding)'{-b,--binding}'[test whether '$words[offset+4]' points to the specified binding]:::_ipsets' )
  ;;
  -B|--bind)
	args=(	'(-b --binding)'{-b,--binding}'[value of the binding]:::_ipsets' )
  ;;
esac

_ips () {
	if [[ $CURRENT -eq ((offset+4)) ]]; then
		local ips=1 default
		local -a vals vals1 vals2 bindings
		vals=( ${${${(f)"$(_call_program ipsets ipset -nL $words[offset+3])"}[4,-1]}//\:/\\:} )
		for i in $vals; do
			if [[ $i = Default\ binding\\:* ]]; then default=${i#Default binding\\: }; continue; fi
			if [[ $i = (Header\\:*|Members\\:) ]]; then continue; fi
			if [[ $i = 'Bindings\:' ]]; then ips=0; continue; fi
			if (( $ips )); then vals1+=$i; else bindings+=${i/ ->/:}; fi
		done
		case $words[offset+2]; in
		  -T|--test)
			vals2=('\:default\::test default binding of the set for --binding')
		  ;;
		  -B|--binding)
			vals2=('\:default\::set default binding of the set')
		  ;;
		  -U|--unbind)
			vals1=()
			vals2=('\:all\::destroy the bindings of all elements of a set')
			if [[ -n "$default" ]]; then
			vals2+=("\:default\::remove default binding of the set to '$default'")
			fi
			_describe -t ipb "IPs from $words[offset+3] set with bindings" bindings
		  ;;
		esac
		_describe -t ips "IPs from $words[offset+3] set" vals1
		_describe -t special_values "special values" vals2
	fi
}

cmds=(-N -X -F -E -W -S -R -A -D -T -B -U -H --create --destroy --flush --rename --swap --save --restore --add --del --test --bind --unbind --help)
listopts=(-n --numeric -s --sorted -L --list -nL -sL -nsL -snL -ns -sn)

_arguments \
	"($cmds $listopts)"{-N,--create}'[create a set]:set name::::_set_types' \
	"($cmds $listopts)"{-X,--destroy}'[destroy specified set (or all if none specified)]:set name:_sets' \
	"($cmds $listopts)"{-F,--flush}'[flush specified set (or all if none specified)]:set name:_sets' \
	"($cmds $listopts)"{-E,--rename}'[rename set]:current set name:_ipsets:new set name:' \
	"($cmds $listopts)"{-W,--swap}'[swap two sets]:::_ipsets:::_ipsets' \
	"($cmds -L --list -q --quiet -nL -sL -nsL -snL)"{-L,--list}'[list the entries and bindings for the specified set (or all if none specified)]:::_sets' \
	"($cmds -L --list -q --quiet -n --numeric -snL -nsL -sL -ns -sn)"-nL'[list the entries and bindings for the specified set (or all if none specified) \- numeric output]:::_sets' \
	"($cmds -L --list -q --quiet -s --sorted  -snL -nsL -nL -ns -sn)"-sL'[list the entries and bindings for the specified set (or all if none specified) \- sorted output]:::_sets' \
	"($cmds $listopts -q --quiet)"{-nsL,-snL}'[list the entries and bindings for the specified set (or all if none specified) \- sorted numeric output]:::_sets' \
	"($cmds $listopts)"{-S,--save}'[save the given set (or all if none specified)]:::_sets' \
	"($cmds $listopts)"{-R,--restore}'[restore a saved session generated by --save from stdin]' \
	"($cmds $listopts)"{-A,--add}'[add an IP to a set]:::_ipsets:IP' \
	"($cmds $listopts)"{-D,--del}'[delete an IP from a set]:::_ipsets:::_ips' \
	"($cmds $listopts)"{-T,--test}'[test wether an IP is in a set or the IP points to the specified binding]:::_ipsets:::_ips' \
	"($cmds $listopts)"{-B,--bind}'[bind the IP in setname to to-setname]:::_ipsets:::_ips' \
	"($cmds $listopts)"{-U,--unbind}'[delete the binding belonging to IP in set setname]:::_ipsets:::_ips' \
	"($cmds $listopts)"{-H,--help}'[print help and settype specific help if settype specified]:::_set_types' \
	"(-q --quiet $listopts)"{-q,--quiet}'[suppress any output to stdout and stderr]' \
	"($cmds -s --sorted  -q --quiet -sL -nsL -snL -ns -sn)"{-s,--sorted}'[sorted output]' \
	"($cmds -n --numeric -q --quiet -nL -nsL -snL -ns -sn)"{-n,--numeric}"[numeric output; don't resolve host names, network names and services]" \
	"($cmds -ns -sn  -q --quiet -nL -sL -nsL -snL -n --numeric -s --sorted)"{-ns,-sn}'[sorted numeric output]' \
	"$args[@]"
