load_module /usr/lib64/nginx/modules/ngx_stream_module.so;

worker_processes auto;

events {
    worker_connections 1024;
}

stream {
    log_format ssl '| Remote Addr: $remote_addr:$server_port | SSL Preread: $ssl_preread_server_name | Forward: $map_forward_ssl | $time_local | $protocol | $status | $bytes_sent | $bytes_received | $session_time |';
    log_format port '| Remote Addr: $remote_addr:$server_port | SSL Preread: $ssl_preread_server_name | Forward: $map_forward_port | $time_local | $protocol | $status | $bytes_sent | $bytes_received | $session_time |';

    # Map all SSL parsed server names to hosts
    map $ssl_preread_server_name $map_forward_ssl {

{% for item in stream_ssl %}
        {{ item.external.domain }} {{ item.internal.domain }}:{{ item.internal.port }};
{% endfor %}
    }

    server {
        access_log /var/log/nginx/nginx_stream_access.log ssl;
        error_log /var/log/nginx/nginx_stream_error.log warn;

        listen 443;

        proxy_pass $map_forward_ssl;
        ssl_preread on;
        proxy_socket_keepalive on;
        resolver 10.1.0.1;
    }

    map $server_port $map_forward_port {
{% for item in stream_ports %}
        {{ item.external }} {{ item.internal }};
{% endfor %}
    }

    server {
{% for item in stream_ports %}
        listen {{ item.external }};
{% endfor %}
        access_log /var/log/nginx/nginx_stream_access.log port;
        error_log /var/log/nginx/nginx_stream_error.log warn;

        listen 443;

        proxy_pass $map_forward_port;
        proxy_socket_keepalive on;
        resolver 10.1.0.1;

    }
}
