#!/usr/bin/env bash
# Wrapper for ad-hoc invocations of the W65816 cross-compiler toolchain.
# Applies the same memory/CPU caps as smokeTest.sh so a runaway backend
# bug (infinite combine, runaway inserter) can't OOM-kill the whole tmux
# scope and take Claude Code down with it.
#
# Usage:
#   scripts/safeCC.sh clang --target=w65816 -O2 -S foo.c -o foo.s
#   scripts/safeCC.sh llc -march=w65816 foo.ll -o foo.s
#
# The first arg is resolved against tools/llvm-mos-build/bin/ if it isn't
# already an absolute or relative path containing a slash.

set -euo pipefail

ulimit -v $((10 * 1024 * 1024))  # 10 GB virtual memory
ulimit -t 90                     # 90 CPU-seconds

if [ $# -lt 1 ]; then
    printf 'usage: %s <tool> [args...]\n' "$0" >&2
    exit 2
fi

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BIN_DIR="$PROJECT_ROOT/tools/llvm-mos-build/bin"

tool="$1"
shift

case "$tool" in
    /*|./*|*/*) exec "$tool" "$@" ;;
    *) exec "$BIN_DIR/$tool" "$@" ;;
esac
