# required to run in a container
daemon off;

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    # basic settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_names_hash_bucket_size 64;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    {{ if .deis_router_gzip }}
    gzip {{ .deis_router_gzip }};
    gzip_comp_level {{ .deis_router_gzipCompLevel }};
    gzip_disable {{ .deis_router_gzipDisable }};
    gzip_http_version {{ .deis_router_gzipHttpVersion }};
    gzip_types {{ .deis_router_gzipTypes }};
    gzip_proxied {{ .deis_router_gzipProxied }};
    gzip_vary {{ .deis_router_gzipVary }};{{ end }}

    # send logs to STDOUT so they can be seen using 'docker logs'
    access_log /dev/stdout;
    error_log /dev/stdout;

    upstream deis-controller {
        server {{ .deis_controller_host }}:{{ .deis_controller_port }};
    }

    server {
        listen 80 default_server;
        server_name ~^deis\.(?<domain>.+)$;
        server_name_in_redirect off;
        port_in_redirect off;

        location / {
            proxy_buffering             off;
            proxy_set_header            Host $host;
            proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_redirect              off;
            proxy_connect_timeout       10;
            proxy_send_timeout          30;
            proxy_read_timeout          30;

            proxy_pass                  http://deis-controller;
        }
    }

    # service definitions for each application
    {{ $domains := .deis_domains }}{{ range $service := .deis_services }}{{ if $service.Nodes }}
    upstream {{ Base $service.Key }} {
        {{ range $upstream := $service.Nodes }}server {{ $upstream.Value }};
        {{ end }}
    }

    server {
        server_name ~^{{ Base $service.Key }}\.(?<domain>.+)${{ range $app_domains := $domains }}{{ if eq (Base $service.Key) (Base $app_domains.Key) }} {{ $app_domains.Value }}{{ end }}{{ end }};

        server_name_in_redirect off;
        port_in_redirect off;

        location / {
            proxy_buffering             off;
            proxy_set_header            Host $host;
            proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_redirect              off;
            proxy_connect_timeout       10;
            proxy_send_timeout          30;
            proxy_read_timeout          30;

            proxy_pass                  http://{{ Base $service.Key }};
        }
    }
    {{ end }}{{ end }}
}
