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

PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OUTPUT_PATH="${1:-"$PROJECT_ROOT/web-build"}"

if [[ -z "${UNITY_EXECUTABLE:-}" ]]; then
  echo "ERROR: Set UNITY_EXECUTABLE to the Unity binary path (Unity.app/Contents/MacOS/Unity)."
  echo "Example:"
  echo '  export UNITY_EXECUTABLE="/Applications/Unity/Hub/Editor/2021.3.*/Unity.app/Contents/MacOS/Unity"'
  exit 2
fi

mkdir -p "$OUTPUT_PATH"

echo "[export_webgl_batchmode] project: $PROJECT_ROOT"
echo "[export_webgl_batchmode] output:  $OUTPUT_PATH"
echo "[export_webgl_batchmode] unity:   $UNITY_EXECUTABLE"

LOG_FILE="$OUTPUT_PATH/unity_webgl_build.log"

"$UNITY_EXECUTABLE" \
  -batchmode -nographics -silent-crashes -quit \
  -projectPath "$PROJECT_ROOT" \
  -executeMethod EventsAppQuest.Editor.WebGLBuild.WebGLBuildEntry.BuildWebGL \
  -outputPath "$OUTPUT_PATH" \
  -logFile "$LOG_FILE"

echo "[export_webgl_batchmode] Done. See log: $LOG_FILE"

