#!/usr/bin/env bash
# The C compiler Spinel calls for an arm64 build (see spinel-cross).
# Rewrites the host Spinel's runtime paths to the arm64 Spinel's, copies
# the generated C into the work directory (which the arm64 root can see),
# and runs a static link with the arm64 root's gcc and glibc.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../../.." && pwd)
host_lib="$(dirname "${SPINEL_HOST:?}")/../lib"
arm_lib="$(dirname "${SPINEL_ARM64:?}")/../lib"
work=${ARM64_WORK:?}
mkdir -p "$work"
args=()
for a in "$@"; do
  case "$a" in
    *"$host_lib"*) a="${a//"$host_lib"/"$arm_lib"}" ;;
    */spinel_out_*.c) cp "$a" "$work/app.c"; a="$work/app.c" ;;
  esac
  args+=("$a")
done
exec "$repo/scripts/arm64.sh" cc -static -s -L"${ARM64_LIB_DIR:?}" "${args[@]}" -lz -lzstd
