#!/bin/bash
# Build all sites: generate Caddyfile, render templates, prepare build/ directory
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
BUILD_DIR="$SCRIPT_DIR/build"

echo "=== Onepager Build ==="

# Clean build directory
rm -rf "$BUILD_DIR"
mkdir -p "$BUILD_DIR"

# 1. Generate Caddyfile
echo "[1/3] Generating Caddyfile..."
"$SCRIPT_DIR/generate-caddyfile.sh" "$SCRIPT_DIR/sites" > "$SCRIPT_DIR/Caddyfile"
echo "  -> Caddyfile written"

# 2. Build each site
echo "[2/3] Building sites..."
count=0
for site_dir in "$SCRIPT_DIR/sites"/*/; do
    [ -f "$site_dir/site.yaml" ] || continue
    domain=$(basename "$site_dir")
    template=$(yq -r '.template // "custom"' "$site_dir/site.yaml")

    mkdir -p "$BUILD_DIR/$domain"

    if [ "$template" = "custom" ]; then
        # Copy everything except site.yaml
        find "$site_dir" -maxdepth 1 -not -name site.yaml -not -path "$site_dir" -exec cp -r {} "$BUILD_DIR/$domain/" \;
        echo "  [custom] $domain"
    else
        template_file="$SCRIPT_DIR/templates/${template}.html"
        if [ ! -f "$template_file" ]; then
            echo "  [ERROR] Template '$template' not found for $domain — skipping" >&2
            continue
        fi
        "$SCRIPT_DIR/render.sh" "$site_dir/site.yaml" "$template_file" > "$BUILD_DIR/$domain/index.html"
        # Copy assets if present
        [ -d "$site_dir/assets" ] && cp -r "$site_dir/assets" "$BUILD_DIR/$domain/"
        echo "  [${template}] $domain"
    fi
    count=$((count + 1))
done
echo "  -> $count sites built"

# 3. Copy shared assets
echo "[3/3] Copying shared assets..."
cp -r "$SCRIPT_DIR/shared" "$BUILD_DIR/shared"
echo "  -> shared/ copied"

# 4. Report
echo "[4/4] Build complete"
echo "=== Build complete: $count sites ==="
