#!/bin/bash
# GCC -wrapper for the darwin8 cross compilers (see tiger-cc).
# mrustc writes Rust inline asm that uses Intel syntax as
#   ".intel_syntax noprefix; mov %0, ebx; ... .att_syntax;"
# GCC (AT&T dialect) substitutes operands as "%esi". GNU as accepts that, but the i386
# assembler of the darwin cross tools is LLVM's (through opt13/bin/clang), which rejects
# '%' registers in noprefix mode. So, for the assembler step only, drop every '%' inside
# .intel_syntax ... .att_syntax regions of the .s file. Everything else runs unchanged.
prog=$1
case "$(basename "$prog")" in
  as)
    args=(); tmps=()
    for a in "$@"; do
      if [[ "$a" == *.s && -f "$a" ]] && grep -q '\.intel_syntax' "$a"; then
        t=$(mktemp /tmp/subwrap.XXXXXX.s)
        awk '{
          line = $0; out = "";
          while (length(line) > 0) {
            if (intel) {
              i = index(line, ".att_syntax");
              seg = (i ? substr(line, 1, i - 1) : line);
              gsub(/%/, "", seg); out = out seg;
              if (i) { intel = 0; line = substr(line, i) } else line = "";
            } else {
              i = index(line, ".intel_syntax");
              if (i) { out = out substr(line, 1, i - 1); intel = 1; line = substr(line, i) }
              else { out = out line; line = "" }
            }
          }
          print out
        }' "$a" > "$t"
        args+=("$t"); tmps+=("$t")
      else
        args+=("$a")
      fi
    done
    "${args[@]}"; rc=$?
    rm -f "${tmps[@]}"
    exit $rc ;;
  *) exec "$@" ;;
esac
