# 
# Insert configuration header here
#
#

# Proxy Setups
upstream omeroweb {
    server 127.0.0.1:4080 fail_timeout=0;
}
upstream thumbnail_backend {
    server 127.0.0.1:8080 fail_timeout=0 max_fails=0;
}
upstream image_region_backend {
    server 127.0.0.1:8081 fail_timeout=0 max_fails=0;
}
upstream pixel_buffer_backend {
    server 127.0.0.1:8082 fail_timeout=0 max_fails=0;
}

# http container exists solely to redirect to https
# DNS name may need to be configured along with hostname if different
server {
    listen 80;
    server_name $hostname;
    return         301 https://$server_name$request_uri;
}

# https container
# DNS name may need to be configured along with hostname if different
server {
    listen 443 ssl;
    server_name $hostname;
    ssl_certificate /etc/ssl/certs/foo.crt;
    ssl_certificate_key /etc/ssl/private/foo.key;

    sendfile on;
    client_max_body_size 0;
    proxy_intercept_errors on;

    # OMERO Plus maintenance page
    location @maintenance_omero {
        root /opt/omero/OMERO.current/etc/templates/error;
        try_files $uri /maintainance.html =502;
    }

    # Thumbnail MS webclient/webgateway uri(s)
    location ~ ^/omero/(webgateway|webclient)/(render_thumbnail|render_birds_eye_view|get_thumbnails)/ {
        rewrite /omero/(.*) /$1 break;
        proxy_pass http://thumbnail_backend;
    }

    # Image Region MS webclient/webgateway uri(s)
    location ~ ^/omero/(webclient|webgateway)/(render_(thumbnail_ngff|image|image_region|image_region_rdef|image_rdef|shape_mask)|get_thumbnails_ngff|histogram_json)/ {
        rewrite /omero/(.*) /$1 break;
        proxy_pass http://image_region_backend;
    }

    # Image Region URI proxy
    location /omero/omero_ms_image_region/ {
        rewrite /omero/(.*) /$1 break;
        gzip on;
        gzip_min_length 0;
        gzip_proxied any;
        gzip_types application/octet-stream;
        proxy_pass http://image_region_backend;
    }

    # Pixel Buffer MS uri(s)
    location /omero/tile/ {
        rewrite /omero/(.*) /$1 break;
        proxy_pass http://pixel_buffer_backend;
    }

    # pathviewer static assets
    location /omero/pathviewer/viewer/static {
        alias /opt/omero/OMERO.current/var/static;
    }

    # omeroweb static assets
    location /omero/static {
        alias /opt/omero/OMERO.current/var/static;
    }

    location @proxy_to_app_omero {
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_buffering off;
        error_page 502 =502 @maintenance_omero;

        proxy_pass http://omeroweb;
    }

    location /omero {
        # checks for static file, if not found proxy to app
        try_files $uri @proxy_to_app_omero;
    }

    location / {
        return 301 /omero$uri;
    }

}
