{% macro nginx_option(option) -%}
  {% if option.value is boolean -%}
    {{ option.key | lower }} {{ 'on' if option.value else 'off' }};
  {% elif option.value | type_debug == 'list' -%}
    {{ option.key | lower }} {{ option.value | join(' ') }};
  {% else -%}
    {{ option.key | lower }} {{ option.value }};
  {% endif -%}
{% endmacro -%}

{% macro nginx_option_block(block) -%}
  {% if block is mapping -%}
    {% for option in (block | d({}) | dict2items) -%}
      {{ nginx_option(option) -}}
    {% endfor -%}
  {% endif -%}
{% endmacro -%}




{{ nginx_option_block(nginx_cfg.root) }}

events {
  {{ nginx_option_block(nginx_cfg.events) }}
}

http {
  {{ nginx_option_block(nginx_cfg.http) }}

  access_log /var/log/nginx/access.log custom;
  include {{ (container_config_mount, 'mime.types') | path_join | quote}};

  geoip2 {{ (container_config_mount, 'geoip.mmdb') | path_join | quote }} {
    auto_reload 30m;
    $geoip_country_code default=RU source=$remote_addr country iso_code;
  }

  server {
    listen 80;
    listen [::]:80;

    server_name apache1.local;

    location / {
      proxy_pass http://{{ hostvars['apache1']['ansible_host'] }};
      proxy_set_header Host $proxy_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Host $server_name;
    }
  }

  server {
    listen 80;
    listen [::]:80;

    server_name apache2.local;

    location / {
      proxy_pass http://{{ hostvars['apache2']['ansible_host'] }};
      proxy_set_header Host $proxy_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Host $server_name;
    }
  }

  server {
    listen 80 default_server;
    listen [::]:80 default_server;

    location / {
      return 404;
    }

    {% if 'nginx_exporter' in groups['all'] -%}
    location /stub_status {
      stub_status;
      # deny all;
      allow {{ hostvars['nginx_exporter']['ansible_host'] }};
    }
    {% endif -%}
  }
}
