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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
blender_bin="${BLENDER_BIN:-blender}"
repository="${BLENDER_EXTENSION_REPO:-user_default}"
build_marker="$(mktemp)"

cleanup() {
  rm -f "$build_marker"
}
trap cleanup EXIT

"$repo_root/build-all.sh"

mapfile -d '' packages < <(
  find "$repo_root/dist" \
    -maxdepth 1 \
    -type f \
    -name '*.zip' \
    -newer "$build_marker" \
    -print0 \
    | sort -z
)

if (( ${#packages[@]} == 0 )); then
  echo "No Blender extension packages were produced by build-all.sh." >&2
  exit 1
fi

for package in "${packages[@]}"; do
  echo "Installing Blender extension: ${package#"$repo_root/"}"
  "$blender_bin" --factory-startup --command extension install-file \
    -r "$repository" \
    -e "$package"
done

echo "Installed and enabled ${#packages[@]} Blender extension(s) in repository '$repository'."

