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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
OUT_DIR="$ROOT_DIR/runtime/ui/ini-panel"
BUILD_DIR="$ROOT_DIR/build/wasm/ini-panel"
OBJ_DIR="$BUILD_DIR/obj"

source "$ROOT_DIR/tools/wasm_incremental_build_lib.sh"

mkdir -p "$OUT_DIR" "$BUILD_DIR" "$OBJ_DIR"

TARGET="linuxcnc_ini_wasm"
: > "$BUILD_DIR/$TARGET.stdout.log"
: > "$BUILD_DIR/$TARGET.stderr.log"

COMMON_FLAGS=(
  -std=c++20
  -O2
  -I"$ROOT_DIR/runtime/core/shims"
  -I"$ROOT_DIR/vendor/linuxcnc/src"
  -I"$ROOT_DIR/vendor/linuxcnc/src/rtapi"
  -I"$ROOT_DIR/vendor/linuxcnc/src/emc"
)

SOURCES=(
  "$ROOT_DIR/vendor/linuxcnc/src/emc/ini/inifile.cc"
  "$ROOT_DIR/runtime/core/linuxcnc_wrap/linuxcnc_ini_wasm.cpp"
)

OBJECTS=()
for source in "${SOURCES[@]}"; do
  obj="$(source_object_path "$source" "$ROOT_DIR" "$OBJ_DIR")"
  OBJECTS+=("$obj")
  compile_wasm_object "$TARGET" "$source" "$obj" "$BUILD_DIR" "${COMMON_FLAGS[@]}"
done

link_wasm_module \
  "$TARGET" \
  "$OUT_DIR/linuxcnc_ini.js" \
  "$BUILD_DIR" \
  -O2 \
  "${OBJECTS[@]}" \
  -s MODULARIZE=1 \
  -s EXPORT_ES6=1 \
  -s ENVIRONMENT=web,node \
  -s ALLOW_MEMORY_GROWTH=1 \
  -s NO_EXIT_RUNTIME=1 \
  -s FORCE_FILESYSTEM=1 \
  -s EXPORTED_FUNCTIONS='["_malloc","_free","_lcini_get_string","_lcini_get_bool","_lcini_tilde_expand"]' \
  -s EXPORTED_RUNTIME_METHODS='["FS","UTF8ToString","stringToUTF8","lengthBytesUTF8"]'
