# Nginx Configuration for PXE Boot Server
#
# This configuration serves:
# - iPXE bootloaders (undionly.kpxe, ipxe.efi)
# - iPXE boot scripts (boot.ipxe)
# - NixOS netboot images (kernel, initrd)
#
# Directory structure:
# /var/lib/pxe-boot/
#   ├── ipxe/          - iPXE bootloaders and scripts
#   │   ├── undionly.kpxe
#   │   ├── ipxe.efi
#   │   └── boot.ipxe
#   └── nixos/         - NixOS boot images
#       ├── bzImage    - Linux kernel
#       └── initrd     - Initial ramdisk

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging format
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;

    # Performance tuning
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    # Disable server tokens for security
    server_tokens off;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/xml text/javascript
               application/json application/javascript application/xml+rss;

    # Custom MIME types for PXE boot files
    types {
        application/octet-stream kpxe;
        application/octet-stream efi;
        text/plain ipxe;
    }

    # PXE Boot Server
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;

        # Root directory for boot files
        root /var/lib/pxe-boot;

        # Increase buffer sizes for large boot images
        client_max_body_size 0;
        client_body_buffer_size 10M;
        client_header_buffer_size 1k;
        large_client_header_buffers 4 8k;

        # Disable buffering for boot files (stream directly)
        proxy_buffering off;

        # Security headers
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-Frame-Options "DENY" always;
        add_header X-XSS-Protection "1; mode=block" always;

        # Boot assets location
        location /boot/ {
            alias /var/lib/pxe-boot/;
            autoindex on;  # Enable directory listing for debugging
            autoindex_exact_size off;
            autoindex_localtime on;

            # Cache control for boot files
            # - Boot scripts (.ipxe): No cache (frequently updated)
            # - Bootloaders (.kpxe, .efi): Short cache (rarely updated)
            # - NixOS images (kernel, initrd): Medium cache (updated per build)

            location ~ \.ipxe$ {
                # iPXE scripts - no cache
                add_header Cache-Control "no-store, no-cache, must-revalidate";
                add_header Pragma "no-cache";
                expires -1;
            }

            location ~ \.(kpxe|efi)$ {
                # iPXE bootloaders - cache for 1 hour
                add_header Cache-Control "public, max-age=3600";
                expires 1h;
            }

            location ~ ^.*/nixos/(bzImage|initrd)$ {
                # NixOS boot images - cache for 15 minutes
                add_header Cache-Control "public, max-age=900";
                expires 15m;

                # Enable range requests for partial downloads
                add_header Accept-Ranges bytes;
            }
        }

        # Direct access to iPXE scripts (alternative path)
        location /ipxe/ {
            alias /var/lib/pxe-boot/ipxe/;
            autoindex on;

            # No cache for boot scripts
            add_header Cache-Control "no-store, no-cache, must-revalidate";
            add_header Pragma "no-cache";
            expires -1;
        }

        # Health check endpoint
        location /health {
            access_log off;
            return 200 "OK\n";
            add_header Content-Type text/plain;
        }

        # Status page (for monitoring)
        location /nginx_status {
            stub_status on;
            access_log off;
            # Restrict access to localhost only
            allow 127.0.0.1;
            allow ::1;
            deny all;
        }

        # Metrics endpoint (Prometheus-compatible)
        location /metrics {
            access_log off;
            # This requires nginx-module-vts or similar
            # Uncomment if you have the module installed
            # vhost_traffic_status_display;
            # vhost_traffic_status_display_format html;

            # For now, return a simple status
            return 200 "# Placeholder for metrics\n";
            add_header Content-Type text/plain;
        }

        # Root path - display welcome page
        location = / {
            return 200 "Centra Cloud PXE Boot Server\n\nAvailable endpoints:\n  /boot/ipxe/boot.ipxe - Main boot script\n  /boot/nixos/ - NixOS boot images\n  /health - Health check\n\nFor more information, see: /boot/\n";
            add_header Content-Type text/plain;
        }

        # Deny access to hidden files
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }

        # Custom error pages
        error_page 404 /404.html;
        location = /404.html {
            return 404 "Not Found: The requested boot file does not exist.\nCheck your PXE configuration and ensure boot images are properly deployed.\n";
            add_header Content-Type text/plain;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            return 500 "Server Error: The PXE boot server encountered an error.\nCheck nginx logs for details: /var/log/nginx/error.log\n";
            add_header Content-Type text/plain;
        }
    }

    # HTTPS server (optional, for enhanced security)
    # Uncomment and configure SSL certificates if needed
    #
    # server {
    #     listen 443 ssl http2;
    #     listen [::]:443 ssl http2;
    #     server_name pxe.centra.local;
    #
    #     ssl_certificate /etc/ssl/certs/pxe-server.crt;
    #     ssl_certificate_key /etc/ssl/private/pxe-server.key;
    #     ssl_protocols TLSv1.2 TLSv1.3;
    #     ssl_ciphers HIGH:!aNULL:!MD5;
    #     ssl_prefer_server_ciphers on;
    #
    #     # Same location blocks as HTTP server above
    #     root /var/lib/pxe-boot;
    #
    #     location /boot/ {
    #         alias /var/lib/pxe-boot/;
    #         autoindex on;
    #     }
    #     # ... (copy other location blocks)
    # }
}
