## -*- mode: shell-script; -*-
##
## Configlet for coexistence mode: flush only FirewallFabrik's own
## prefixed chains, leaving other tools' chains untouched.
##
## Configlets support simple macro language with these constructs:
## {{$var}} is variable expansion
## {{if var}} is conditional operator.
##
reset_fwf_chains_v4() {
  prefix="$1"

  # For each table, remove FWF jump rules from built-in chains (in
  # reverse order to keep line numbers stable), then flush and delete
  # FWF's own chains.  We do not check /proc/net/ip_tables_names
  # because it is absent on systems using the iptables-nft backend;
  # instead we query iptables directly and suppress errors.
  for table in filter nat mangle; do
    # Remove jump rules targeting our prefixed chains from built-in chains.
    for chain in INPUT FORWARD OUTPUT PREROUTING POSTROUTING; do
      $IPTABLES {{$opt_wait}} -t "$table" -L "$chain" -n --line-numbers 2>/dev/null \
        | grep "${prefix}_" | awk '{print $1}' | sort -rn \
        | while read -r rulenum; do
            $IPTABLES {{$opt_wait}} -t "$table" -D "$chain" "$rulenum" 2>/dev/null
          done
    done

    # Flush all our prefixed chains first, then delete them in a
    # second pass.  A single pass fails when sub-chains (e.g.
    # fwf_C...) sort alphabetically before their parent chains
    # (fwf_INPUT) -- the delete would fail because the parent still
    # references the sub-chain.
    $IPTABLES {{$opt_wait}} -t "$table" -L -n 2>/dev/null \
      | grep "^Chain ${prefix}_" | awk '{print $2}' \
      | while read -r chain; do
          $IPTABLES {{$opt_wait}} -t "$table" -F "$chain" 2>/dev/null
        done
    $IPTABLES {{$opt_wait}} -t "$table" -L -n 2>/dev/null \
      | grep "^Chain ${prefix}_" | awk '{print $2}' \
      | while read -r chain; do
          $IPTABLES {{$opt_wait}} -t "$table" -X "$chain" 2>/dev/null
        done
  done
}

reset_fwf_chains_v6() {
  prefix="$1"

  for table in filter nat mangle; do
    for chain in INPUT FORWARD OUTPUT PREROUTING POSTROUTING; do
      $IP6TABLES {{$opt_wait}} -t "$table" -L "$chain" -n --line-numbers 2>/dev/null \
        | grep "${prefix}_" | awk '{print $1}' | sort -rn \
        | while read -r rulenum; do
            $IP6TABLES {{$opt_wait}} -t "$table" -D "$chain" "$rulenum" 2>/dev/null
          done
    done

    $IP6TABLES {{$opt_wait}} -t "$table" -L -n 2>/dev/null \
      | grep "^Chain ${prefix}_" | awk '{print $2}' \
      | while read -r chain; do
          $IP6TABLES {{$opt_wait}} -t "$table" -F "$chain" 2>/dev/null
        done
    $IP6TABLES {{$opt_wait}} -t "$table" -L -n 2>/dev/null \
      | grep "^Chain ${prefix}_" | awk '{print $2}' \
      | while read -r chain; do
          $IP6TABLES {{$opt_wait}} -t "$table" -X "$chain" 2>/dev/null
        done
  done
}
