{% if not helpers.empty('OPNsense.unboundplus.dots.dot') %}
{%   set all_dots = [] %}
{%   set all_forwards = [] %}
{%   set local = [] %}
{%   for type, dots in helpers.toList('OPNsense.unboundplus.dots.dot')|groupby("type") %}
{%     for dot in dots %}
{%       if dot.enabled == '1' %}
{%         if dot.server.startswith('127.') or dot.server == '::1' %}
{%           do local.append('1') %}
{%         endif %}
{%         if type == 'dot' %}
{%           do all_dots.append(dot) %}
{%         else %}
{%           do all_forwards.append(dot) %}
{%         endif %}
{%       endif %}
{%     endfor %}
{%   endfor %}
{%   if local|length > 0 %}
server:
  do-not-query-localhost: no
{%   endif %}

# Forward zones
{%  for domain, forwards in all_forwards|groupby("domain", default=".") %}
{% set domain_opts = namespace(forward_tcp_upstream=False, forward_first=False) %}
forward-zone:
  name: "{{ domain }}"
{%    for forward in forwards %}
  forward-addr: {{ forward.server }}{% if forward.port %}@{{ forward.port }}{% endif %}
{%    set domain_opts.forward_tcp_upstream = domain_opts.forward_tcp_upstream or forward.forward_tcp_upstream == '1' %}
{%    set domain_opts.forward_first = domain_opts.forward_first or forward.forward_first == '1' %}

{%    endfor %}
{%    if domain_opts.forward_tcp_upstream %}
  forward-tcp-upstream: yes
{%    endif %}
{%    if domain_opts.forward_first  %}
  forward-first: yes
{%    endif %}
{%  endfor %}

{%   if all_dots|length > 0 %}
# Forward zones over TLS
server:
  tls-cert-bundle: /usr/local/etc/ssl/cert.pem
{%     for domain, dots in all_dots|groupby("domain", default=".") %}
{% set domain_opts = namespace(forward_first=False) %}

forward-zone:
  name: "{{ domain }}"
  forward-tls-upstream: yes
{%       for dot in dots %}
  forward-addr: {{ dot.server }}{% if dot.port %}@{{ dot.port }}{% endif %}{% if dot.verify %}#{{ dot.verify }}{% endif %}
{%    set domain_opts.forward_first = domain_opts.forward_first or dot.forward_first == '1' %}

{%       endfor %}
{%    if domain_opts.forward_first  %}
  forward-first: yes
{%    endif %}
{%     endfor %}
{%   endif %}
{% endif %}
