#!/usr/bin/env bash
# alloy — JS-to-C++ compiler driver
#
# Usage:
#   ./alloy init [<dir>] [--build]
#   ./alloy build [<dir>] [-o output] [--no-inline-html]
#   ./alloy run [<dir>] [--time|--benchmark] [-- app-args…]
#   ./alloy -compile input.js [-o output] [-cflags "extra c++ link flags"]
#   ./alloy --print-c input.js
#
# Environment:
#   CXX       C++ compiler for emitted programs (default: c++)
#   ALLOY_BIN Path to alloy_bin (default: auto-detected)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# -- Locate the compiler binary ------------------------------------------------
if [ -n "${ALLOY_BIN:-}" ] && [ -x "$ALLOY_BIN" ]; then
    BIN="$ALLOY_BIN"
elif [ -n "${JSC_BIN:-}" ] && [ -x "$JSC_BIN" ]; then
    # Backwards compatibility for legacy env var
    BIN="$JSC_BIN"
elif [ -x "$SCRIPT_DIR/alloy_bin" ]; then
    BIN="$SCRIPT_DIR/alloy_bin"
elif [ -x "$SCRIPT_DIR/jsc_bin" ]; then
    # Backwards compatibility for old binary name
    BIN="$SCRIPT_DIR/jsc_bin"
else
    echo "alloy: compiler binary not found (expected alloy_bin). Run 'make' first." >&2
    exit 1
fi

exec "$BIN" "$@"
