#!/usr/bin/env bash
# End-to-end check that every SDK treats a closed reader as success.
#
# Each probe writes 2 MiB of raw bytes through a process-wired CliEmitter, then
# finishes with an error event and the intended exit code 3. Piped into
# `head -c 10`, the reader closes the pipe long before the payload is written,
# and the spec says that is not a failure: every SDK must exit 0. Where
# /dev/full exists, the same probes also prove the other half of the rule: a
# write that fails for any other reason exits 4 with `output_write_failed`.
# On Windows, /dev/full belongs to the MSYS layer only: a native probe
# redirected there writes successfully, as to NUL, so that half needs a host
# whose /dev/full is the operating system's own device.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOTPATH="$(cd "$SCRIPT_DIR/.." && pwd)"
PYTOOL="${AFDATA_PYTOOL:-python3}"
TEST_TMP="$(mktemp -d "${TMPDIR:-/tmp}/afdata-closed-reader.XXXXXX")"
trap 'rm -rf "$TEST_TMP"' EXIT

fail() {
  printf 'closed-reader e2e failed: %s\n' "$1" >&2
  exit 1
}

# Probe commands run from their SDK directory, so each is a function.
probe_rust() { "$RUST_PROBE"; }
probe_go() { "$GO_PROBE"; }
probe_python() { PYTHONPATH="$ROOTPATH/python" "$PYTOOL" "$ROOTPATH/tests/closed_reader/closed_reader.py"; }
probe_typescript() {
  (cd "$ROOTPATH/typescript" && npm run build --silent && node --import tsx "$ROOTPATH/tests/closed_reader/closed_reader.ts")
}

full_device=false
case "$(uname -s)" in
  MINGW* | MSYS* | CYGWIN*)
    printf 'closed-reader: the failed-write half needs a native /dev/full, which Windows does not have\n' ;;
  *) [ -w /dev/full ] && full_device=true ;;
esac

(cd "$ROOTPATH" && cargo build --quiet --example closed_reader)
RUST_PROBE="${CARGO_TARGET_DIR:-$ROOTPATH/target}/debug/examples/closed_reader"
[ -x "$RUST_PROBE" ] || RUST_PROBE="$RUST_PROBE.exe"
GO_PROBE="$TEST_TMP/closedreader"
(cd "$ROOTPATH/go" && go build -o "$GO_PROBE" ./internal/closedreader)

for sdk in rust go python typescript; do
  stderr_file="$TEST_TMP/$sdk.stderr"
  head_file="$TEST_TMP/$sdk.head"

  set +e
  "probe_$sdk" 2>"$stderr_file" | head -c 10 >"$head_file"
  status="${PIPESTATUS[0]}"
  set -e

  [ "$(wc -c <"$head_file" | tr -d ' ')" = "10" ] || fail "$sdk: reader did not receive its 10 bytes"
  [ "$status" = "0" ] || fail "$sdk: closed reader must exit 0, got $status"

  if [ "$full_device" = true ]; then
    set +e
    "probe_$sdk" 2>"$stderr_file" >/dev/full
    status="$?"
    set -e
    [ "$status" = "4" ] || fail "$sdk: a failed write must exit 4, got $status"
    grep -q 'output_write_failed' "$stderr_file" || fail "$sdk: output_write_failed was not reported"
  fi
  printf 'closed-reader ok: %s\n' "$sdk"
done
