map $ssl_client_s_dn $ssl_client_s_dn_cn {
	default "no_client_cert";
	~(^|,)CN=(?<CN>[^,]+) $CN;
}

server {
    listen 443 ssl;
    # TODO: nginx doesn't natively support env variable expansion here, but
    # you can eventually create a custom Dockerfile/entrypoint to populate
    # this value from an env variable rather than hard-coding.
    server_name vtn1.bsch.ca;
    root /dev/null;
    
    # next 3 lines force clients to provide a client cert, and ensure that the
    # cert is trusted by the chain in clientssl.crt.
    ssl_verify_client on;
    ssl_client_certificate /etc/ssl/clientssl.crt;
    ssl_verify_depth 2;

    # Don't advertise
    server_tokens off;

    # Don't merge slashes
    merge_slashes off;

    location / {
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header  Host             $http_host;
        proxy_set_header  X-Forwarded-Proto $scheme;
        proxy_set_header  X-Forwarded-Ssl on;
        proxy_set_header  X-Forwarded-Port $server_port;
        proxy_set_header  X-Forwarded-Host $host;

        # these next two headers are consumed by EPRI to validate client cert
        # CN vs. EPRI VEN Common Name.
        proxy_set_header  SSL_CLIENT_S_DN_CN $ssl_client_s_dn_cn; 
        proxy_set_header  HTTPS true;
        
        proxy_redirect    off;
        proxy_pass http://vtn-rails:8080;
    }

    ssl_certificate /etc/ssl/ssl.crt;
    ssl_certificate_key /etc/ssl/ssl.key;
}

server {
    listen 443 ssl;
    server_name admin.vtn1.bsch.ca;
    root /dev/null;

    # Don't advertise
    server_tokens off;

    # Don't merge slashes
    merge_slashes off;

    location / {
        proxy_set_header  X-Real-IP        $remote_addr;
        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header  Host             $http_host;
        proxy_set_header  X-Forwarded-Proto $scheme;
        proxy_set_header  X-Forwarded-Ssl on;
        proxy_set_header  X-Forwarded-Port $server_port;
        proxy_set_header  X-Forwarded-Host $host;

        proxy_set_header  HTTPS true;

        proxy_redirect    off;
        proxy_pass http://vtn-rails:8080;
    }

    ssl_certificate /etc/ssl/adminssl.crt;
    ssl_certificate_key /etc/ssl/adminssl.key;
}
