{%- set TRUE_VALUES = ['y', 'yes', '1', 'true'] %}
{%- set server_alias_list =  slave_parameter.get('server-alias', '').split() %}
{%- set ssl_proxy_verify = ('' ~ slave_parameter.get('ssl-proxy-verify', '')).lower() in TRUE_VALUES %}
{%- set host_list = [] %}
{%- for host in [slave_parameter.get('custom_domain')] + server_alias_list %}
{%-   if host not in host_list %}
{%-     do host_list.append(host) %}
{%-   endif %}
{%- endfor %}
{%- set http_backend_host_list = [] %}
{%- set https_backend_host_list = [] %}
{%- for host in host_list %}
{%-   do http_backend_host_list.append('http://%s:%s' % (host, slave_parameter['cached_port'])) %}
{%-   do https_backend_host_list.append('http://%s:%s' % (host, slave_parameter['ssl_cached_port'])) %}
{%- endfor %}

# SSL-disabled backends
{{ http_backend_host_list|join(', ') }} {
  bind {{ slave_parameter['local_ipv4'] }}
# Rewrite part
  proxy / {{ slave_parameter.get('backend_url', '') }} {
    try_duration {{ slave_parameter['proxy_try_duration'] }}s
    try_interval {{ slave_parameter['proxy_try_interval'] }}ms

    transparent
    timeout {{ slave_parameter['request_timeout'] }}s
{%- if ssl_proxy_verify %}
{%-   if 'path_to_ssl_proxy_ca_crt' in slave_parameter %}
    ca_certificates {{ slave_parameter['path_to_ssl_proxy_ca_crt'] }}
{%-   endif %}
{%- else %}
    insecure_skip_verify
{%- endif %}
  }
  log / {{ slave_parameter.get('access_log_cache_direct') }} "{remote} - {>REMOTE_USER} [{when}] \"{method} {uri} {proto}\" {status} {size} \"{>Referer}\" \"{>User-Agent}\" {latency_ms}" {
    rotate_size 0
  }

  errors {{ slave_parameter.get('error_log_cache_direct') }} {
    rotate_size 0
  }
}

# SSL-enabled backends
{{ https_backend_host_list|join(', ') }} {
  bind {{ slave_parameter['local_ipv4'] }}
  proxy / {{ slave_parameter.get('https_backend_url', '') }} {
    try_duration {{ slave_parameter['proxy_try_duration'] }}s
    try_interval {{ slave_parameter['proxy_try_interval'] }}ms
    transparent
    timeout {{ slave_parameter['request_timeout'] }}s
{%- if ssl_proxy_verify %}
{%-   if 'path_to_ssl_proxy_ca_crt' in slave_parameter %}
    ca_certificates {{ slave_parameter['path_to_ssl_proxy_ca_crt'] }}
{%-   endif %}
{%- else %}
    insecure_skip_verify
{%- endif %}
  }
  log / {{ slave_parameter.get('access_log_cache_direct') }} "{remote} - {>REMOTE_USER} [{when}] \"{method} {uri} {proto}\" {status} {size} \"{>Referer}\" \"{>User-Agent}\" {latency_ms}" {
    rotate_size 0
  }

  errors {{ slave_parameter.get('error_log_cache_direct') }} {
    rotate_size 0
  }
}
