@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "REPO_ROOT=%~dp0"
set "BLENDER_ROOT=%REPO_ROOT%blender"
set "DIST_DIR=%REPO_ROOT%dist"

if not defined BLENDER_BIN set "BLENDER_BIN=blender"
if not defined BLENDER_EXTENSION_REPO set "BLENDER_EXTENSION_REPO=user_default"

if not exist "%BLENDER_ROOT%" (
  echo No Blender extension directory found at "%BLENDER_ROOT%". 1>&2
  exit /b 1
)

if not exist "%DIST_DIR%" mkdir "%DIST_DIR%"
if errorlevel 1 exit /b 1

set /a EXTENSION_COUNT=0

for /r "%BLENDER_ROOT%" %%F in (blender_manifest.toml) do (
  set "EXTENSION_ID="
  set "EXTENSION_VERSION="

  for /f "tokens=1,* delims==" %%A in ('findstr /b /c:"id =" "%%F"') do set "EXTENSION_ID=%%B"
  for /f "tokens=1,* delims==" %%A in ('findstr /b /c:"version =" "%%F"') do set "EXTENSION_VERSION=%%B"

  set "EXTENSION_ID=!EXTENSION_ID: =!"
  set "EXTENSION_ID=!EXTENSION_ID:"=!"
  set "EXTENSION_VERSION=!EXTENSION_VERSION: =!"
  set "EXTENSION_VERSION=!EXTENSION_VERSION:"=!"

  if not defined EXTENSION_ID (
    echo Could not read the extension id from "%%F". 1>&2
    exit /b 1
  )
  if not defined EXTENSION_VERSION (
    echo Could not read the extension version from "%%F". 1>&2
    exit /b 1
  )

  for %%D in ("%%~dpF.") do set "SOURCE_DIR=%%~fD"
  set "PACKAGE=%DIST_DIR%\!EXTENSION_ID!-!EXTENSION_VERSION!.zip"

  echo Building Blender extension: !EXTENSION_ID! !EXTENSION_VERSION!
  "%BLENDER_BIN%" --factory-startup --command extension build ^
    --source-dir "!SOURCE_DIR!" ^
    --output-filepath "!PACKAGE!"
  if errorlevel 1 exit /b 1

  echo Installing Blender extension: !PACKAGE!
  "%BLENDER_BIN%" --factory-startup --command extension install-file ^
    -r "%BLENDER_EXTENSION_REPO%" ^
    -e "!PACKAGE!"
  if errorlevel 1 exit /b 1

  set /a EXTENSION_COUNT+=1
)

if !EXTENSION_COUNT! equ 0 (
  echo No Blender extension manifests found under "%BLENDER_ROOT%". 1>&2
  exit /b 1
)

echo Installed and enabled !EXTENSION_COUNT! Blender extension(s) in repository "%BLENDER_EXTENSION_REPO%".
exit /b 0
