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

cache_dir="$1"
cache_stub_file="$2"
shift 2

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

export EM_CACHE="$(abspath "$cache_dir")"
export EM_CONFIG="$(abspath "$ZX_CONFIG")"

# This script should be invoked as:
#   `$bin_root/third_party/external/emscripten/generate_cache`.
# The runfiles tree for this script should be a sibling in the same directory:
#   `$bin_root/third_party/external/emscripten/generate_cache.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_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"
export PYTHON=$(which python3.6)

mkdir --parents "$cache_dir"

# Build a stub file that requires all of the dependencies that emscripten may
# want to cache.
"$workspace_dir/upstream/emscripten/emcc" \
  -s USE_GLFW=3 -s USE_ZLIB=1 -s USE_BZIP2=1 \
  "$@" \
  "$cache_stub_file" -o cache_stub.wasm
