#!/usr/bin/env bash

die() {
  printf '%s\n' "$*" >&2
  exit 1
}

showUsage() {
  echo Usage: "$0 [debug|debug-source-map]"
  exit 1
}

if [ $# -gt 1 ]; then
    showUsage
fi

if [ $# = 1 ]; then
  if [ "$1" != "debug" ] && [ "$1" != "debug-source-map" ]; then
    showUsage
  fi
fi

npm ci --prefix webgl

if [ "$1" = "debug" ]; then
  NPM_SCRIPT_TARGET=build-debug-nosourcemap
  TRY_USE_CLANG_FORMAT=1
elif [ "$1" = "debug-source-map" ]; then
  NPM_SCRIPT_TARGET=build-dev
  TRY_USE_CLANG_FORMAT=1
else
  NPM_SCRIPT_TARGET=build
  TRY_USE_CLANG_FORMAT=0
fi

JS_FORMATTER=cat
JS_FORMATTER_OPTS=
if [ $TRY_USE_CLANG_FORMAT -ne 0 ]; then
  if [ -x "$(command -v clang-format)" ]; then
    JS_FORMATTER=clang-format
    JS_FORMATTER_OPTS=--style=file:"webgl/.clang-format"
  else
    echo "clang-format not found; will not apply formatting to generated javascript file"
  fi
fi

npm run "$NPM_SCRIPT_TARGET" --prefix webgl

ASYGL_OUTPUT_FROM_WEBPACK=webgl/dist/gl.js
test -f "$ASYGL_OUTPUT_FROM_WEBPACK" || die "Missing $ASYGL_OUTPUT_FROM_WEBPACK"

ASYGL_OUTPUT=base/webgl/asygl.js
{
  cat webgl/license;
  echo "/* license for gl-matrix: ";
  curl -L https://cdn.jsdelivr.net/gh/toji/gl-matrix@refs/heads/master/LICENSE.md;
  echo "*/";
  "$JS_FORMATTER" $JS_FORMATTER_OPTS "$ASYGL_OUTPUT_FROM_WEBPACK";
} > "$ASYGL_OUTPUT"
