#!/bin/bash
# C compiler wrapper used by mrustc (CC_<triple>) for Mac OS X 10.4 Tiger targets.
# Runs the GCC 13.4 cross compiler (Jazzzny gcc-13-branch-panther + darwin-xtools ld64-236)
# mounted at /w (TW) inside the rg-tiger container (copy of ~/ppc-darwin/opt13 + sdk on precision) natively on the host.
# Usage: invoked as tiger-cc-<triple> via symlink, e.g. tiger-cc-powerpc-apple-darwin8
TW=${TW:-/w}
self=$(basename "$0")
triple=${self#tiger-cc-}
case "$triple" in
  # Any G3 and up (CPU subtype ALL, as Tiger's own programs), tuned for the G4e. TIGER_PPC_CPU can change
  # it: -mcpu=7400 makes a ppc7400 file, which a G3 refuses to start.
  powerpc-apple-darwin8) arch_flags="${TIGER_PPC_CPU:--mcpu=750 -mtune=7450}" ;;
  i686-apple-darwin8)    arch_flags="-march=prescott -mtune=generic" ;;
  *) echo "tiger-cc: unknown triple $triple" >&2; exit 2 ;;
esac
# mrustc passes -fPIC (harmless on Darwin) and may pass -pthread (not meaningful on Darwin)
# mrustc passes its arguments in a response file (@x_cmd.txt, double-quoted words): expand it
# so the checks below see them.
expanded=()
for a in "$@"; do
  if [[ "$a" == @* && -f "${a#@}" ]]; then eval "expanded+=($(cat "${a#@}"))"; else expanded+=("$a"); fi
done
set -- "${expanded[@]}"
# When linking (no -c/-S/-E), add the Tiger compat shim and link libgcc (incl. the unwinder,
# libgcc_eh) statically: Tiger has no libgcc_s with GCC 13's symbols.
link=1
for a in "$@"; do case "$a" in -c|-S|-E|-M|-MM) link=0 ;; esac; done
extra=()
if [ $link = 1 ] && [ -z "$TIGER_NO_COMPAT" ]; then
  extra=(/rg/build/compat/tigercompat-$triple.o -static-libgcc)
fi
args=()
for a in "$@"; do
  case "$a" in
    -pthread) ;;                                  # libSystem has pthreads
    -O1) args+=("${TIGER_OPT:--O1}") ;;           # mrustc maps -O to -O1; TIGER_OPT can raise it
    *) args+=("$a") ;;
  esac
done
exec "$TW/opt13/bin/$triple-gcc" -wrapper "$(dirname "$(readlink -f "$0")")/gcc-subwrap" -B"$TW/opt13/bin/" --sysroot="$TW/sdk/MacOSX10.4u.sdk" \
  -mmacosx-version-min=10.4 $arch_flags ${TIGER_CFLAGS} "${args[@]}" "${extra[@]}"
