#!/bin/bash
# Generate Caddyfile from sites/*/site.yaml
# Single :80 block with host-based matchers (Traefik handles TLS)
set -euo pipefail

SITES_DIR="${1:-sites}"

cat <<'HEADER'
{
    auto_https off
    admin off
}

:80 {
HEADER

cat <<'SHARED'
    # Shared assets available on all domains under /shared/
    handle /shared/* {
        root * /srv
        file_server
    }
SHARED

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 host list
    hosts="$domain"
    if [ -n "$aliases" ]; then
        for alias in $aliases; do
            hosts="$hosts $alias"
        done
    fi

    # Sanitize domain for matcher name (replace . and - with _)
    matcher=$(echo "$domain" | tr ".-" "__")

    cat <<EOF
    @${matcher} host ${hosts}
    handle @${matcher} {
        root * /srv/${domain}
        file_server
    }
EOF
done

cat <<'FOOTER'
    handle {
        respond "Not Found" 444
    }
}
FOOTER
