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

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

"$blender_root/scripts/build.sh"
archive="$(find "$repo_root/dist" -maxdepth 1 -type f -name 'material_id_baker-*.zip' -printf '%T@ %p\n' | sort -n | tail -1 | cut -d' ' -f2-)"

if [[ -z "$archive" ]]; then
  echo "No Material ID Baker package was produced." >&2
  exit 1
fi

"$blender_bin" --factory-startup --command extension install-file \
  -r "$repository" -e "$archive"

echo "Installed $archive into Blender repository '$repository'."
