# w3cs CPU server: single TLS origin for page + relay websockets.
# WebGPU and crypto.randomUUID need a secure context, and an https page
# may only open wss sockets, so nginx fronts both backends on one origin.
map $http_upgrade $connection_upgrade {
    default upgrade;
    ""      close;
}

# Seat number (from the /seatN/ named capture) to relay port.
map $seat_number $seat_port {
    1 8145;
    2 8146;
    3 8147;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name london-cpu-worker.war3replays.com;

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

    # Seats: /seatN/* fronts seat N's relay on 814N. The regex capture builds
    # the backend port; with variables in proxy_pass nginx does not append
    # the query string on its own.
    location ~ ^/seat(?<seat_number>[1-3])(?<seat_path>/.*)$ {
        proxy_pass http://127.0.0.1:$seat_port$seat_path$is_args$args;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        proxy_buffering off;
    }

    # Relay websockets (signaling and the ws-transport planes), seat 1
    # directly on the origin for old links and the SSH-tunnel lab flow.
    location ~ ^/(signal|reliable|frame|control)(/|$) {
        proxy_pass http://127.0.0.1:8145;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
        proxy_buffering off;
    }

    # Content-addressed resource bundles served by the relay.
    location /resource-bundle/ {
        proxy_pass http://127.0.0.1:8145;
        proxy_read_timeout 120s;
    }

    # Test index, live page, web modules (no-store python server).
    location / {
        proxy_pass http://127.0.0.1:8150;
    }
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # Let's Encrypt HTTP-01 challenges must stay on plain HTTP.
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}
