#!/usr/bin/env bash
# Custom linker for wasm32-wasip2: ignore rustc's object files and emit the
# Gleam-built component (written by build.rs to target/gleam-extension.wasm).
#
# Zed Install Dev Extension runs `cargo build --target wasm32-wasip2` and then
# copies this crate's .wasm to extension.wasm — so the "link" product must be
# the real guest.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="${GLEAM_EXTENSION_WASM:-$ROOT/target/gleam-extension.wasm}"

if [[ ! -f "$SRC" ]]; then
  echo "gleam-wasm-linker: missing $SRC" >&2
  echo "  build.rs should have run \`gleam export zed-extension\` first." >&2
  echo "  Set GLEAM to a wasm-capable gleam binary if needed." >&2
  exit 1
fi

# Expand rustc response files (@path) into a flat arg list, then find -o OUT.
OUT=""
args=()
for arg in "$@"; do
  if [[ "$arg" == @* ]]; then
    resp="${arg#@}"
    if [[ -f "$resp" ]]; then
      # shellcheck disable=SC2207
      mapfile -t lines <"$resp"
      args+=("${lines[@]}")
    fi
  else
    args+=("$arg")
  fi
done

i=0
while [[ $i -lt ${#args[@]} ]]; do
  case "${args[$i]}" in
    -o)
      i=$((i + 1))
      OUT="${args[$i]:-}"
      ;;
    -o*)
      OUT="${args[$i]#-o}"
      ;;
    --output=*)
      OUT="${args[$i]#--output=}"
      ;;
  esac
  i=$((i + 1))
done

if [[ -z "$OUT" ]]; then
  echo "gleam-wasm-linker: could not find -o output path in linker args" >&2
  printf '  %q\n' "$@" >&2
  exit 1
fi

mkdir -p "$(dirname "$OUT")"
cp -f "$SRC" "$OUT"
echo "gleam-wasm-linker: installed Gleam component → $OUT" >&2
