#!/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

# Resolve repo root: script may be invoked from webgl/ (via npm run) or repo root.
# Use readlink -f to resolve symlinks so SCRIPT_DIR is always the real path.
SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

npm ci --prefix "$REPO_ROOT/webgl"

(cd "$REPO_ROOT/webgl" && npx tsc --noEmit) || die "TypeScript type checking failed"

ASYGL_OUTPUT="$REPO_ROOT/base/webgl/asygl.js"

ESBUILD_ARGS="src/gl.ts --bundle --format=iife --target=es2017 --loader:.glsl=text"

# debug: unminified, no sourcemap (clean file for debugging/editing)
# debug-source-map: unminified, with inline sourcemap
# default: minified (esbuild + terser)
if [ "$1" = "debug-source-map" ]; then
  ESBUILD_ARGS="$ESBUILD_ARGS --sourcemap=inline"
elif [ "$1" != "debug" ]; then
  ESBUILD_ARGS="$ESBUILD_ARGS --minify"
fi

TMPJS=$(mktemp)
TJSTMP=$(mktemp)
(cd "$REPO_ROOT/webgl" && npx esbuild $ESBUILD_ARGS --outfile="$TMPJS")
cp "$TMPJS" "$ASYGL_OUTPUT"
rm -f "$TMPJS"

# Post-minify with terser for additional compression.
# Skip in debug mode: the debug options must inhibit minification.
if [ "$1" != "debug" ] && [ "$1" != "debug-source-map" ]; then
  cat "$ASYGL_OUTPUT" | terser -m -c > "$TJSTMP" 2>/dev/null
  cat "$TJSTMP" > "$ASYGL_OUTPUT"
fi
rm -f "$TJSTMP"
