#!/bin/bash
# Generate nginx.conf from sites/*/site.yaml
# Reads domain and aliases from each site config, outputs full nginx.conf to stdout
set -euo pipefail

SITES_DIR="${1:-sites}"

cat <<'HEADER'
worker_processes auto;
events { worker_connections 1024; }

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    sendfile on;
    gzip on;
    gzip_types text/css application/javascript image/svg+xml;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;

HEADER

for site_dir in "$SITES_DIR"/*/; do
    [ -f "$site_dir/site.yaml" ] || continue
    domain=$(basename "$site_dir")

    # Read aliases from site.yaml
    aliases=""
    if command -v yq &>/dev/null; then
        aliases=$(yq -r '.aliases // [] | .[]' "$site_dir/site.yaml" 2>/dev/null || true)
    fi

    # Build server_name list
    server_names="$domain"
    if [ -n "$aliases" ]; then
        server_names="$domain $(echo "$aliases" | tr '\n' ' ')"
    fi

    cat <<EOF
    server {
        listen 80;
        server_name ${server_names};
        root /usr/share/nginx/html/${domain};
        index index.html;
        error_page 404 /index.html;

        location ~* \.(jpg|jpeg|png|gif|ico|svg|woff2|woff|css|js)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }
    }

EOF
done

cat <<'FOOTER'
    # Catch-all: reject unknown hosts
    server {
        listen 80 default_server;
        return 444;
    }
}
FOOTER
