#compdef iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore arptables ebtables

local curcontext="$curcontext" i ret=1
local -a state line expl cmds rcmds ropts rules states prev args

case $service in
  iptables-save | ip6tables-save)
    _arguments -s \
      {-c,--counters}'[include values of packet and byte counters in output]' \
      {-t,--table}'[specify table]:table:(filter nat mangle raw security)'
    return
  ;;
  iptables-restore | ip6tables-restore)
    _arguments -s \
      {-c,--counters}'[restore the values of all packet and byte counters]' \
      {-n,--noflush}"[don't flush the previous contents of the table]"
    return
  ;;
esac

rcmds=( -A --append -D --delete -I --insert -R --replace )
cmds=(
  -L --list -F --flush -Z --zero -N --new --new-chain -X --delete-chain
  -P --policy -E --rename-chain -h --help -V --version
)
ropts=(
  -p --proto --protocol -s --src --source -d --dst --destination -j --jump -i
  --in-interface -o --out-interface -f --fragment -c --set-counters
)

prev=( ${words[1,CURRENT-1]} )
case ${prev[${prev[(I)-p|--proto|--protocol]}+1]} in
  tcp)
    args=(
      '--tcp-flags[match based on TCP flags in a packet]: :->tcp-flags: :->tcp-flags'
      '--syn[match packets with the SYN flag set]'
      '--tcp-option[match based on TCP options]:option'
    )
  ;&
  udp)
    args+=(
      '(--sport --source-port)'{--sport,--source-port}'[match packets based on source port]:*^!:port:_ports'
      '(--dport --destination-port)'{--dport,--destination-port}'[match packets based on destination port]:*^!:port:_ports'
    )
  ;;
  icmp) args=( '--icmp-type[match specified ICMP type]:*^!:ICMP type:->icmp-types' ) ;;
esac

case ${prev[${prev[(I)-j|--jump]}+1]} in
  DNAT) args+=( '(--to --to-destination)'{--to,--to-destination}':address' ) ;;
  DSCP)
    args+=(
      '--set-dscp[set the DSCP field]:value'
      '--set-dscp-class[set the DiffServ class]:class'
    )
  ;;
  ECN) args+=( '--ecn-tcp-remove[remove all ECN bits from TCP header]' ) ;;
  LOG)
    args+=(
      '--log-level[specify level of logging]:log level:(debug info notice warning err crit alert emerg)'
      '--log-prefix[specify prefix string for log message]:string'
      '--log-tcp-sequence[log TCP sequence numbers]'
      '--log-tcp-options[log TCP options]'
      '--log-ip-options[log IP options]'
    )
  ;;
  MARK) args+=( '--set-mark[set fwmark in packet]:number' ) ;;
  REDIRECT|MASQUERADE) args+=( '--to-ports[port (range) to map to]:port range:_ports' ) ;;
  REJECT) args+=( '--reject-with[drop packet and send reply]:reject type:->reject-types' ) ;;
  SNAT) args+=( '(--to --to-source)*'{--to,--to-source}'[specify address to map source to]:address' ) ;;
  TCPMSS)
    args+=(
      '--set-mss[explicitly set MSS option]:value'
      '--clamp-mss-to-pmtu[automatically clamp MSS value]'
    )
  ;;
  TOS) args+=( '--set-tos[set type of service field]:type of service:->tos' ) ;;
  ULOG)
    args+=(
      '--ulog-nlgroup[specify netlink group used for logging]:netlink group'
      '--ulog-prefix[specify prefix string for log message]:string'
      '--ulog-cprange[specify size of each packet to be passed]:size (bytes)'
      '--ulog-qthreshold[specify threshold of in-kernel queue]:size'
    )
  ;;
esac

# loop through all -m options preceding the cursor
local i=1
typeset -U args
while
  (( i=words[(ib.i.)-m|--match]+1 ))
(( i<CURRENT )); do
  case ${words[i]} in
    addrtype)
      args+=(
        '--src-type[match if the source address is of given type]:type:->address-types'
        '--dst-type[match if the destination address is of given type]:type:->address-types'
        '(--limit-iface-out)--limit-iface-in[limit to interface the packet is coming in]'
        '(--limit-iface-in)--limit-iface-out[limit to interface the packet is going out]'
      )
    ;;
    ah)
      args+=( '--ahspi[match SPIs in AH header]:*^!:spi' )
      [[ $service = ip6* ]] && args+=(
        '--ahlen[total length of this header]:length (octets)'
        '--ahres[match if the reserved field is filled with zero]'
      )
    ;;
    bpf)
      args+=(
        '--object-pinned[pass a path to a pinned eBPF object]:path:_files'
        '--bytecode[pass BPF byte code as generated by nfbpf_compile]:code'
      )
    ;;
    cgroup)
      args+=(
        '--path[match cgroup2 membership]:path:_files -W /sys/fs/cgroup'
        '--cgroup[match cgroup net_cls classid]:classid'
      )
    ;;
    cluster)
      args+=(
        '--cluster-total-nodes[set number of total nodes in cluster]:number'
        '--cluster-local-node[set the local node number ID]:number'
        '--cluster-local-nodemask[set the local node number ID mask]:mask'
        '--cluster-hash-seed[set seed value of the Jenkins hash]:value'
      )
    ;;
    comment) args+=( '--comment[add comment to rule]:comment' ) ;;
    connbytes)
      args+=(
        '--connbytes:size (min\:[max])'
        '--connbytes-dir:packets:(original reply both)'
        '--connbytes-mode:mode:(packets bytes avgpkt)'
      )
    ;;
    connlabel)
      args+=(
        '--label[match if label name has been set on a connection]:label'
        '--set[set label on connection]'
      )
    ;;
    connlimit)
      args+=(
        --connlimit-{upto,above}:connections
        '--connlimit-mask:prefix length'
        --connlimit-{s,d}addr
      )
    ;;
    connmark) args+=( --mark:value ) ;;
    conntrack)
      args+=(
        '--ctstate[match packet state]:state:->cfstates'
	'--ctproto[match protocol]:protocol:_ports'
	'--ctorigsrc[match original source address]:*^!:network:_hosts'
	'--ctorigdst[match original destination address]:*^!:network:_hosts'
	'--ctreplsrc[match reply source address]:*^!:network:_hosts'
	'--ctrepldst[match reply destination address]:*^!:network:_hosts'
        --ct{orig,repl}{src,dst}port':port:_ports'
	'--ctstatus[match internal conntrack states]:state:(NONE EXPECTED SEEN_REPLY ASSURED)'
	'--ctexpire[match remaining lifetime]:time'
        '--ctdir:direction:(original reply)'
      )
    ;;
    cpu) args+=( --cpu:number ) ;;
    dccp)
      args+=(
        --{s,d,source-,destination-}port:port:_ports
        '--dccp-types:type:_sequence compadd - REQUEST RESPONSE DATA ACK DATAACK CLOSEREQ CLOSE RESET SYNC SYNCACK INVALID'
        --dccp-option:option
      )
    ;;
    devgroup) args+=( --{src,dst}group:name ) ;;
    dscp)
      args+=(
        '--dscp[match DSCP field]:value'
	'--dscp-class[match the DiffServ class]:class'
      )
    ;;
    dst) args+=( --dst-len:length --dst-opts:type ) ;;
    ecn) args+=( --ecn-{tcp-{cwr,ece},ip-ect} ) ;;
    esp) args+=( '--espspi[match SPIs in ESP header]:*^!:spi' ) ;;
    frag)
      args+=(
        --fragid:id --fraglen:length
        --frag{res,first,more,last}
      )
    ;;
    hashlimit)
      args+=(
        --hashlimit-{upto,above,burst}:amount
        '--hashlimit-mode:object:_sequence compadd - srcip srcport dstip dstport'
        --hashlimit-{src,dst}mask:prefix
        --hashlimit-name:name
        --hashlimit-htable-size:buckets
        --hashlimit-htable-max:entries
        --hashlimit-htable-{expire,gcinterval}:msec
        --hashlimit-rate-match
        --hashlimit-rate-intervale:sec
      )
    ;;
    hbh) args+=( --hbh-len:length --hbh-opts:type ) ;;
    helper) args+=( '--helper[match packets related to a conntrack-helper]:helper:(ftp)' ) ;;
    hl) args+=( --hl-{eq,lt,gt}:value ) ;;
    icmp) args+=( --icmp-type:type ) ;;
    icmp6) args+=( --icmpv6-type:type ) ;;
    iprange) args+=( --{src,dst}-range':IP range' ) ;;
    ipv6header)
      args+=(
        --soft
        '--header:header(hop dst route frag auth esp none prot)'
      )
    ;;
    ipvs)
      args+=(
        --ipvs --vproto:protocol --vaddr:address
        --vport{,ctl}':port:_ports'
        '--vdir:directory:(ORIGINAL REPLY)'
        '--vmethod:method:(GATE IPIP MASQ)'
      )
    ;;
    length) args+=( '--length[match packet length]:length' ) ;;
    limit)
      args+=(
        '--limit[specify max matches limit]:number'
	'--limit-burst[specify max burst before limit applies]:number'
      )
    ;;
    mac) args+=( '--mac-source[match source ethernet address]:*^!:ethernet address' ) ;;
    mark) args+=( '--mark[match fwmark in packet]:number' ) ;;
    multiport)
      args+=(
	'--source-ports[match packets based on source ports]:ports:->port-list'
	'(--dports --destination-ports)'{--dports,--destination-ports}'[match packets based on destination ports]:ports:->port-list'
	'--ports[match where source and destination ports are equal]:ports:->port-list'
      )
    ;;
    nfacct) args+=( --nfacct-name:name ) ;;
    osf) args+=( --genre:string --{ttl,log}:level ) ;;
    owner)
      args+=(
        '--uid-owner[match packet by user id of creating process]:user id'
	'--gid-owner[match packet by ggroup id of creating process]:group id'
	'--pid-owner[match packet by process id of creating process]:process id:_pids'
	'--sid-owner[match packet by session id of creating process]:session id'
        --suppl-groups --socket-exists
      )
    ;;
    physdev)
      args+=(
        '--physdev-in[specify bridge port via which packet is received]:name'
        '--physdev-out[specify bridge port via which packet is sent]:name'
        --physdev-is-{in,out,bridged}
      )
    ;;
    pkttype) args+=( '--pkt-type[match link-layer packet type]:type:(unicast broadcast multicast)' ) ;;
    policy)
      args+=(
        '--dir:direction:(in out)'
        '(--strict)--pol:policy:(none ipsec)'
        '(--pol)--strict'
        --reqid:id --spi:id
        '--proto:encapsulation protocol:(ah esp ipcomp)'
        '--mode:encapsulation mode:(tunnel transport)'
        --tunnel-{src,dst}:addr --next
      )
    ;;
    quota) args+=( '--quota:quota (bytes)' ) ;;
    rateest)
      args+=(
        --rateest-{delta,lt,gt,eq}
        --rateest{,1,2}:name
        --rateest-{bps,pps}{,1,2}:value
      )
    ;;
    realm) args+=( --realm:value ) ;;
    recent)
      args+=(
        --name:name --r{source,dest} --mask:netmask
        '(--rcheck --update --remove)--set'
        '(--set --update --remove)--rcheck'
        '(--set --rcheck --remove)--update'
        '(--set --rcheck --update)--remove'
        --seconds:seconds --reap --hitcount:hits --rttl
      )
    ;;
    rpfilter) args+=( --loose --validmark --accept-local --invert ) ;;
    rt)
      args+=(
        --rt-type:type --rt-segsleft:number --rt-len:length
        --rt-0-{res,not-strict} --rt-0-addrs:address
      )
    ;;
    sctp)
      args+=(
        --{s,d,source-,destination-}port:port:_ports
        '--chunk-types:match type:(all any only):chunk type'
      )
    ;;
    set)
      args+=(
        '--match-set:set: :flag'
        --return-nomatch --update-counters --update-subcounters
        --{packet,byte}s-{eq,lt,gt}:value
      )
    ;;
    socket) args+=( --transparent --nowildcard --restore-skmark ) ;;
    state)
      args+=(
        '--state[match packet state]:state:->states'
      )
    ;;
    statistic) args+=( --mode:mode --{probability,every,packet}:value ) ;;
    string)
      args+=(
        '--algo:strategy:(bm kmp)'
        --{from,to}:offset
        --{,hex}string:pattern
        -icase
      )
    ;;
    tcp)
      args+=(
        --{s,d,source-,destination-}port:port:_ports
        '--tcp-flags:mask:->tcp-flags:comp:->tcp-flags'
        --syn --tcp-option:option
      )
    ;;
    tcpmss) args+=( --mss:value ) ;;
    time)
      args+=(
        --date{start,stop}:date --time{start,stop}:time
        --{month,week}days:day
        --contiguous --kerneltz
      )
    ;;
    tos) args+=( '--tos[match type of service field]:type of service:->tos' ) ;;
    ttl) args+=( '--ttl-'{eq,lt,gt}':TTL value' ) ;;
    u32) args+=( '--u32:tests' ) ;;
    udp) args+=( --{s,d,source-,destination-}port:port:_ports ) ;;
  esac
done

if (( CURRENT > 2 )); then
  if [[ $words[CURRENT-1] = (|\\)\! && ! -prefix - ]]; then
    args+=( '*: :compadd -S "" - -' )
  else
    args+=( '*:negation:(!)' )
  fi
fi

_arguments -C -s \
  '(-)'{-h,--help}'[print program information]' \
  '(-)'{-V,--version}'[print version information]' \
  '(-h --help -V --version)'{-t,--table}'[specify table]:table:(filter nat mangle raw security)' \
  "($rcmds $cmds)"{-A,--append}'[append rules to end of specified chain]:chain:->chains' \
  {-C,--check}'[check for the existence of a rule]' \
  "($rcmds $cmds -c --set-counters)"{-D,--delete}'[delete rules from specified chain]:chain:->chains::rule number:->rulenums' \
  "($rcmds $cmds)"{-I,--insert}'[insert rules before specified rule number]:chain:->chains::rule number:->rulenums' \
  "($rcmds $cmds)"{-R,--replace}'[replace a rule]:chain:->chains::rule number:->rulenums' \
  "($rcmds "${(j. .)cmds:#(-Z|--zero)}" $ropts)"{-L,--list}'[list rules in selected chain]::chain:->chains:rule number:->rulenums' \
  '(-L --list -S --list-rules)'{-S,--list-rules}'[list rules in the form of options to iptables]::chain:->chains::rule number:->rulenums' \
  "($rcmds $cmds $ropts)"{-F,--flush}'[flush specified chain (delete all rules)]::chain:->chains' \
  "($rcmds "${(j. .)cmds:#(-L|--list)}" $ropts)"{-Z,--zero}'[zero the packet and byte counters]::chain:->chains' \
  "($rcmds $cmds)"{-N,--new,--new-chain}'[create a new user-defined chain]:chain name' \
  "($rcmds $cmds)"{-X,--delete-chain}'[delete a user-defined chain]:: :->user-chains' \
  "($rcmds $cmds)"{-P,--policy}'[set the policy for a chain to given target]:chain:->chains:target:->targets' \
  "($rcmds $cmds)"{-E,--rename-chain}'[rename a user-defined chain]:old chain:->user-chains:new chain name' \
  "($cmds -p --proto --protocol)"{-p,--proto,--protocol}'[specify protocol of rule]:*^!:protocol:(! tcp udp icmp all)' \
  "($cmds -s --src --source)"{-s,--src,--source}'[specify source]:*^!:network:_sequence _hosts' \
  "($cmds -d --dst --destination)"{-d,--dst,--destination}'[specify destination]:*^!:network:_sequence _hosts' \
  "($cmds -j --jump)"{-j,--jump}'[specify rule target]:target:->targets' \
  "($cmds -g --goto)"{-g,--goto}'[jump to chain with no return]:target:->targets' \
  "($cmds -i --in-interface)"{-i,--in-interface}'[specify interface via which packet is received]:*^!:interface:_net_interfaces' \
  "($cmds -o --out-interface)"{-o,--out-interface}'[specify interface via which packet is to be sent]:*^!:interface:_net_interfaces' \
  "($cmds -f --fragment)"{-f,--fragment}'[match second or further fragments only]' \
  "($cmds -D --delete -c --set-counters)"{-c,--set-counters}'[initialise packet and byte counters]:packets: :bytes' \
  '(-v --verbose)'{-v,--verbose}'[enable verbose output]' \
  '(-w --wait)'{-w,--wait}'[specify maximum wait to acquire xtables lock before giving up]: :_numbers -u seconds -d 1 wait' \
  '(-n --numeric)'{-n,--numeric}'[print IP addresses and port numbers in numeric format]' \
  '(-x --exact)'{-x,--exact}'[expand numbers (display exact values)]' \
  '--line-numbers[print line numbers when listing]' \
  '--modprobe=[specify command to load modules with]:command:_command_names -e' \
  "($cmds)*"{-m,--match}'[extended match (may load extension)]:extension:(addrtype ah bpf cgroup cluster comment connbytes connlabel connlimit connmark conntrack cpu dccp devgroup dscp dsr ecn esp eui64 frag hashlimit hbh helper hl icmp icmp6 iprange ipv6header ipvs length limit mac mark mh multiport nfacct osf owner physdev pkttype policy quota rateest realm recent rpfilter rt sctp set socket state statistic string tcp tcpmss time tos ttl u32 udp unclean)' \
  "$args[@]" && ret=0

case "$state" in
  targets)
    _wanted targets expl 'builtin target' compadd \
        ACCEPT DROP QUEUE RETURN DNAT DSCP ECN LOG MARK MASQUERADE MIRROR \
	REDIRECT REJECT SNAT TCPMSS TOS ULOG && ret=0
  ;&
  user-chains)
    _wanted chains expl 'user-defined chain' compadd \
	${${${${(M)${(f)"$(_call_program chains $words[1] \
	${(kv)opt_args[(i)-t|--table]} -nL \
	2>/dev/null)"}:#Chain*}#* }%% *}:#(INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING)} && ret=0
  ;;
  chains)
    _wanted chains expl 'chain' compadd \
        ${${${(M)${(f)"$(_call_program chains $words[1] \
	${(kv)opt_args[(i)-t|--table]} -nL \
	2>/dev/null)"}:#Chain*}#* }%% *} && ret=0
  ;;
  rulenums)
    rules=(
      ${${${(f)"$(_call_program chains $words[1] ${(kv)opt_args[(i)-t|--table]} \
      --line-numbers -nL ${(v)opt_args[(i)-D|--delete|-I|--insert|-R|--replace]%:*} \
      2>/dev/null)"}[3,-1]}/ ##/:}
    )
    _describe -t rulenum 'rule number' rules && ret=0
  ;;
  tcp-flags)
    _values -s , 'tcp flag' SYN ACK FIN RST URG PSH NONE ALL && ret=0
  ;;
  icmp-types)
    _wanted icmp-types expl 'icmp type' compadd \
        ${${${(f)"$(_call_program icmp-types ${words[1]} -p icmp --help \
	2>/dev/null)"}[(r)any,-1]## #}%% *} && ret=0
  ;;
  reject-types)
    _wanted reject-types expl 'reject type' compadd \
        ${${${(f)"$(_call_program icmp-types ${words[1]} -j REJECT --help \
	2>/dev/null)"}[(r)*types:,-1]## #}[2,-1]%% *} && ret=0
  ;;
  *states)
    states=( NEW ESTABLISHED RELATED INVALID )
    [[ "$state" = cf* ]] && states+=( SNAT DNAT )
    _values -s , 'state' $states && return
  ;;
  address-types)
    _wanted address-types expl 'address type' compadd \
        UNSPEC UNICAST LOCAL BROADCAST ANYCAST MULTICAST \
        BLACKHOLE UNREACHABLE PROHIBIT THROW NAT XRESOLVE && ret=0
  ;;
  port-list)
    compset -P '*,'
    if compset -S ',*'; then
      _ports && ret=0
    else
      _ports -qS, && ret=0
    fi
  ;;
  tos)
    _wanted tos expl 'type of service' compadd \
       ${${${(f)"$(_call_program tos ${words[1]} -m tos --help \
       2>/dev/null)"}[(r)*16*,-1]## #}%% *} && ret=0
  ;;
esac

return ret
