#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 1 ]]; then
  echo "usage: scripts/build-macos-cross OUTPUT_DIRECTORY" >&2
  exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
output_absolute="$(cd "$1" && pwd -P)"
if [[ "$output_absolute" != "$repo_root/"* ]]; then
  echo "output directory must remain inside the repository" >&2
  exit 2
fi
if [[ "$(uname -s)" != "Linux" || "$(uname -m)" != "x86_64" ]]; then
  echo "macOS cross-builds require a Linux x86_64 Docker host" >&2
  exit 2
fi

zig_wheel_url="https://files.pythonhosted.org/packages/"
zig_wheel_url+="3e/ed/7b79023aa27ceb5d461ecf761181e7c33c57bbc1a6256a39535d1c7083d2/"
zig_wheel_url+="ziglang-0.16.0-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64."
zig_wheel_url+="musllinux_1_1_x86_64.whl"
zig_wheel_hash="9fcda73f62b851dd72a54b710ad40a209896db14cfb13649e62191243556342b"
zig_requirement="ziglang @ ${zig_wheel_url}#sha256=${zig_wheel_hash}"
zig_package="$(
  uvx --from "$zig_requirement" python - <<'PY'
from pathlib import Path

import ziglang

print(Path(ziglang.__file__).parent)
PY
)"
if [[ ! -d "$zig_package" ]]; then
  echo "resolved ziglang package is missing: $zig_package" >&2
  exit 2
fi

image="ghcr.io/pyo3/maturin@sha256:2665227312dd1eab1c29c70a001dc8aac53155a2d048bede3b2df7f1691c8e38"
docker run --rm \
  --workdir /io \
  --env "CARGO_TARGET_DIR=/tmp/foamwiki-target" \
  --env "CARGO_TARGET_AARCH64_APPLE_DARWIN_LINKER=/tools/linkers/zigcc-aarch64-macos11" \
  --env "CARGO_TARGET_X86_64_APPLE_DARWIN_LINKER=/tools/linkers/zigcc-x86_64-macos10.12" \
  --env "CARGO_ZIGBUILD_ZIG_PATH=/tools/linkers/python-zig" \
  --env "PYTHONPATH=/tools/ziglang-package" \
  --env "HOST_UID=$(id -u)" \
  --env "HOST_GID=$(id -g)" \
  --volume "$repo_root:/io:ro" \
  --volume "$output_absolute:/output" \
  --volume "$repo_root/scripts/release:/tools/linkers:ro" \
  --volume "$zig_package:/tools/ziglang-package/ziglang:ro" \
  --entrypoint /bin/sh \
  "$image" \
  -c 'set -eu
    test "$(/tools/linkers/python-zig version)" = "0.16.0"
    test "$(maturin --version)" = "maturin 1.14.1"
    test "$(rustc --version)" = "rustc 1.96.0 (ac68faa20 2026-05-25)"
    if find / -xdev -name "MacOSX*.sdk" -print -quit 2>/dev/null | grep -q .; then
      echo "refusing to cross-build with an Apple SDK on a Linux host" >&2
      exit 2
    fi
    unset SDKROOT
    rustup target add aarch64-apple-darwin x86_64-apple-darwin
    maturin build --release --locked --zig \
      --target aarch64-apple-darwin --out /output
    maturin build --release --locked --zig \
      --target x86_64-apple-darwin --out /output
    chown -R "$HOST_UID:$HOST_GID" /output'
