#!/bin/bash
set -euo pipefail

# Minimal GCC-compatible assembler driver for the Tooie decomp on macOS.
# Clang preprocesses assembly; a sibling GNU mips-linux-gnu-as emits MIPS ELF.

cpp_args=()
as_args=()
input_path=""
output_path=""

while (($#)); do
    arg="$1"
    shift
    case "$arg" in
        -o)
            output_path="$1"
            shift
            ;;
        -I|-D|-U|-include|-isystem)
            value="$1"
            shift
            cpp_args+=("$arg" "$value")
            if [[ "$arg" == "-I" ]]; then
                as_args+=("$arg" "$value")
            fi
            ;;
        -I*)
            cpp_args+=("$arg")
            as_args+=("$arg")
            ;;
        -D*|-U*|-nostdinc)
            cpp_args+=("$arg")
            ;;
        -march=*|-mabi=*|-mgp32|-mfp32|-mips*|-G*)
            as_args+=("$arg")
            ;;
        -gdwarf|-gdwarf-2|-g)
            as_args+=("--gdwarf-2")
            ;;
        -x)
            shift
            ;;
        -c|-fno-pic|-mno-abicalls)
            ;;
        -*)
            echo "mips-linux-gnu-gcc wrapper: unsupported option: $arg" >&2
            exit 2
            ;;
        *)
            if [[ -n "$input_path" ]]; then
                echo "mips-linux-gnu-gcc wrapper: multiple inputs unsupported" >&2
                exit 2
            fi
            input_path="$arg"
            ;;
    esac
done

if [[ -z "$input_path" || -z "$output_path" ]]; then
    echo "mips-linux-gnu-gcc wrapper: expected one input and -o output" >&2
    exit 2
fi

preprocessed_path="$(mktemp "${TMPDIR:-/tmp}/tooie-asm.XXXXXX")"
trap 'rm -f "$preprocessed_path"' EXIT

/usr/bin/clang -E -P -x assembler-with-cpp "${cpp_args[@]}" \
    "$input_path" -o "$preprocessed_path"
"$(dirname "$0")/mips-linux-gnu-as" "${as_args[@]}" \
    -o "$output_path" "$preprocessed_path"
