#!/bin/bash
# rustc-wrapper
#
# Use this script in the `[build]`,`rustc-wrapper` section of your
# `.cargo/config.toml` configuration file to correctly set the
# `RUST_TARGET_PATH` environment variable before running rustc.
#
# This is to workaround a bug whereby `rustc --print cfg` fails when you
# use a custom `target.json` file, unless `RUST_TARGET_PATH` is set to the
# directory containing the target description.

# `cargo` passes "rustc " as the first parameter to the wrapper; pop it off
shift

# Extract the target config JSON from the `config.toml`
#
# NOTE: We assume that this wrapper script is in the root of your project, and
# that the `build.target` value is relative to the location of the same.
#
TARGET_JSON_FILE=$(cargo config -Z unstable-options get --format json-value build.target 2>/dev/null || echo "")

if [ ! -z "${TARGET_JSON_FILE}" ]; then
  TARGET_JSON_DIR=$(dirname "${TARGET_JSON_FILE//\"/}")

  # Work out where we are and which rustup we're wrapping
  #BASEDIR=$(dirname "$0")
  BASEDIR=`pwd`

  # Set the env variable
  export RUST_TARGET_PATH=$(realpath "${BASEDIR}/${TARGET_JSON_DIR}")
fi

RUSTC=$(rustup which rustc)

# Now let rustc do its thing
#"${RUSTC}" --remap-path-prefix "$(pwd)=." $@
"${RUSTC}" $@
