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

function abspath() {
  # Trim off any leading PWD/, if present, and then add it back.
  echo $(pwd)/"${1#"$(pwd)/"}"
}

# This script should be invoked as:
#   `$bin_root/third_party/external/emscripten/emcc`.
# The runfiles tree for this script should be a sibling in the same directory:
#   `$bin_root/third_party/external/emscripten/emcc.runfiles`.
# Directly inside the runfiles root is a directory for every external workspace,
# include emscripten.
workspace_dir="$(abspath "$0").runfiles/$ZX_EMSCRIPTEN_WORKSPACE_NAME"
export EM_BINARYEN_ROOT="$workspace_dir/$ZX_BINARYEN_ROOT"
export EM_CACHE="$workspace_dir/$ZX_CACHE"
export EM_CONFIG="$workspace_dir/$ZX_CONFIG"
export EM_EMSCRIPTEN_ROOT="$workspace_dir/$ZX_EMSCRIPTEN_ROOT"
export EM_LLVM_ROOT="$workspace_dir/$ZX_LLVM_ROOT"
export EM_NODE_JS="$workspace_dir/$ZX_NODE_JS"
export LD_LIBRARY_PATH="$workspace_dir/$ZX_RPATH_ROOT"

export PATH="$PATH:$ZX_LLVM_ROOT"

# Restrict parallelism to single-core execution. Bazel is managing the number of
# jobs we want building in each action. Using internal parallelism will defeat
# the load-balancing techniques of the Bazel server.
# Plus, Bazel has swapped out the implementation of `multiprocessing`, which
# prevents `emcc` from using parallel execution at all.
export EMCC_CORES=1
exec "$workspace_dir/emcc" "$@"
