# n-OS-tr nginx site
# Terminates TLS, serves blobs directly from disk, forwards Blossom
# authenticated operations to ginxsom over FastCGI.

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    # Redirect plain HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    http2 on;
    server_name _;

    # Self-signed cert generated on first boot
    ssl_certificate     /etc/ssl/n-os-tr/fullchain.pem;
    ssl_certificate_key /etc/ssl/n-os-tr/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # Uploads can be large
    client_max_body_size 100m;

    # Blobs root — nginx serves GET directly from disk
    root /var/www/html;
    index index.html;

    # 1) Landing page / any static docs
    location = / {
        try_files /index.html =404;
    }

    # 2) Blob retrieval: GET /<64-hex sha256>
    #    First try the file on disk; if absent, fall back to ginxsom
    #    (which may have metadata but no bytes, or may need to 404 with
    #    a proper Blossom error).
    location ~ "^/(?<blobhash>[a-f0-9]{64})$" {
        root /var/www/blobs;
        try_files /$blobhash @ginxsom;
    }

    # 3) Blossom authenticated operations go to ginxsom over FastCGI
    location = /upload         { try_files $uri @ginxsom; }
    location = /mirror         { try_files $uri @ginxsom; }
    location = /report         { try_files $uri @ginxsom; }
    location /list/            { try_files $uri @ginxsom; }
    location /blossom-admin/   { try_files $uri @ginxsom; }

    # 4) c-relay websocket endpoint: wss://host/relay -> ws://127.0.0.1:8888/
    location = /relay {
        proxy_pass http://127.0.0.1:8888/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
    }

    # 5) c-relay admin API/UI
    location /admin/ {
        proxy_pass http://127.0.0.1:8888/api/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location @ginxsom {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME /usr/local/bin/ginxsom/ginxsom-fcgi;
        fastcgi_pass unix:/run/ginxsom/ginxsom-fcgi.sock;
        fastcgi_read_timeout 300s;
    }
}
