#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
blender_bin="${BLENDER_BIN:-blender}"
dist_dir="$repo_root/dist"

mapfile -d '' manifests < <(
  find "$repo_root/blender" -type f -name blender_manifest.toml -print0 | sort -z
)

if (( ${#manifests[@]} == 0 )); then
  echo "No Blender extension manifests found under $repo_root/blender." >&2
  exit 1
fi

mkdir -p "$dist_dir"

for manifest in "${manifests[@]}"; do
  source_dir="$(dirname "$manifest")"
  echo "Building Blender extension: ${source_dir#"$repo_root/"}"
  "$blender_bin" --factory-startup --command extension build \
    --source-dir "$source_dir" \
    --output-dir "$dist_dir"
done

echo "Built ${#manifests[@]} Blender extension(s) into $dist_dir."

