#!/usr/bin/env bash

set -e

# Workaround for
# https://github.com/kripken/emscripten/issues/4542

# Consider a project with this structure:
#
# ├── src
# │   ├── bin
# │   │   └── prog.rs
# │   └── lib.rs
# ├── benches
# │   └── b.rs
# ├── examples
# │   └── a.rs
# └── tests
#     └── t.rs
#
# We expect that the artifacts will be generated in
#
# `target/wasm32-unknown-emscripten/{debug,release}/deps/`
# (for tests and benches)
#
# `target/wasm32-unknown-emscripten/{debug,release}/examples/`
# for examples
#
# `target/wasm32-unknown-emscripten/{debug,release}/`
# for main programs (`main.rs` and `bin/*.rs`)
#
# Because of https://github.com/kripken/emscripten/issues/4542
# the script must be executed from where the dependencies are.

path="$(dirname "${1}")"
file="$(basename "${1}")"
base="$(basename "${path}")"

if [[ "${base}" != "deps" ]] && [[ "${base}" != "examples" ]]; then
  # main programs requeries the artifacts in `${path}/deps`
  cd "${path}/deps"
  exec node "../${file}"
else
  # all deps of tests, benches and examples are in `${path}` dir
  cd "${path}"
  exec node "${file}"
fi

