#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 wether '$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[@]"
