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

if [[ -z "${BUN_REAL:-}" ]]; then
  printf '%s\n' 'ci-gate bun shim: BUN_REAL is required' >&2
  exit 127
fi

if [[ -n "${CI_GATE_RESULTS_DIR:-}" && -n "${CI_GATE_ROOT:-}" && "${1:-}" == "test" ]]; then
  for arg in "${@:2}"; do
    case "$arg" in
      --reporter|--reporter=*|--reporter-outfile|--reporter-outfile=*)
        printf '%s\n' "ci-gate bun shim: conflicting reporter argument: $arg" >&2
        exit 64
        ;;
    esac
  done
  rel="$(realpath --relative-to="$CI_GATE_ROOT" "$PWD")"
  slug="workspace-${rel//\//-}"
  outfile="$CI_GATE_RESULTS_DIR/raw/${slug}.junit.xml"
  mkdir -p "$(dirname "$outfile")"
  exec "$BUN_REAL" test --reporter=junit --reporter-outfile="$outfile" "${@:2}"
fi

exec "$BUN_REAL" "$@"
