#!/usr/bin/env bash
# moon's C compiler/linker driver for debug builds. It never builds tcc; it uses one that exists:
#   1. $TCC, if set
#   2. the vendored tinycc, if already built (`just tcc-build` puts it in _build/tcc)
#   3. `tcc` on PATH (e.g. from `pixi install`, see pixi.toml)
#   scripts/tcc/tcc --which   prints the tcc it would use (exit 1 if none)
# moon adds -DMOONBIT_NATIVE_NO_SYS_HEADER whenever the compiler is tcc; that
# mode compiles the system parts of the runtime out (it expects to be JIT-ed
# inside moon), so a standalone executable would not link. Drop it.
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
if [ -n "${TCC:-}" ]; then
  tcc="$TCC"
elif [ -x "$root/_build/tcc/bin/tcc" ]; then
  tcc="$root/_build/tcc/bin/tcc"
elif tcc="$(command -v tcc)"; then
  :
else
  echo "error: no tcc found. Install one (pixi install, or your package manager), set TCC=/path/to/tcc," >&2
  echo "       or build the vendored one with: just tcc-build" >&2
  exit 127
fi
if [ "${1:-}" = "--which" ]; then echo "$tcc"; exit 0; fi
args=()
for a in "$@"; do
  [ "$a" = "-DMOONBIT_NATIVE_NO_SYS_HEADER" ] || args+=("$a")
done
# tcc does not link libm by default; the font rasteriser needs it. Add it on link steps only.
link=1
for a in "${args[@]}"; do
  case "$a" in -c|-ar) link=0 ;; esac
done
if [ "$link" = 1 ]; then args+=(-lm); fi
exec "$tcc" "${args[@]}"
