. "$BST_LIB"

# zlib ships NO CLI on this image: the distro builds libz.a static-only (see
# recipes-core/zlib/zlib_%.bbappend) and drops poky's shared example binaries
# (examplesh/minigzipsh). So zlib is exercised through an in-image consumer that
# statically links libz.a. Two are covered here:
#   file(1)  — libmagic links zlib; `file -z` inflates a gzip stream (glibc-runnable,
#              the reliable proof).
#   tcl      — Tcl's built-in `zlib` command is a true compress->decompress round-trip
#              (the stronger proof). tclsh is a large distinct module; a second, late
#              spawn in a memory-heavy suite can hit the browser per-process memory
#              budget (rc=126 ENOMEM, hardwarejs#7-class) — that is a runtime-env
#              limit, not a zlib/tcl defect, so it is a skip, not a fail.

tmp=${TMPDIR:-/tmp}/bst-zlib.$$
line="the quick brown fox jumps over the lazy dog 0123456789"
i=0; while [ $i -lt 64 ]; do printf '%s\n' "$line"; i=$((i+1)); done > "$tmp.in" 2>/dev/null

# --- Consumer 1: file(1) libmagic inflate via zlib (glibc-runnable) -----------
if command -v file >/dev/null 2>&1 && command -v gzip >/dev/null 2>&1; then
  gzip -c "$tmp.in" > "$tmp.gz" 2>/dev/null
  # `file -z` decompresses the gzip stream through zlib and re-identifies the
  # inner content as text; if libz were not linked/working this would fail.
  check_out zlib/file-inflate "text" sh -c "file -z '$tmp.gz'"
else
  bst_skip zlib/file-inflate "file or gzip not installed on this image"
fi

# --- Consumer 2: Tcl zlib true round-trip -------------------------------------
if command -v tclsh >/dev/null 2>&1; then
  out=$(tclsh "$BST_DATA/zlib-roundtrip.tcl" 2>&1); rc=$?
  rseen=$(printf '%s\n' "$out" | grep -c '^R-')
  case "$out" in
    *ZLIB-RT-OK*)
      bst_ok zlib/tcl-roundtrip ;;
    *"annot allocate memory"*)
      bst_skip zlib/tcl-roundtrip "tclsh ENOMEM on a late spawn — browser per-process memory budget (hardwarejs#7-class), not a zlib/tcl defect" ;;
    *)
      if [ "$rc" -ge 128 ] && [ "$rseen" -eq 0 ]; then
        # crashed before any output (SIGILL) — a real runtime regression
        bst_notok zlib/tcl-roundtrip "tclsh crashed before output (rc=$rc) — runtime regression"
      else
        bst_notok zlib/tcl-roundtrip "rc=$rc $(_bst_1line "$out")"
      fi ;;
  esac
else
  bst_skip zlib/tcl-roundtrip "tclsh not installed on this image"
fi

rm -f "$tmp.in" "$tmp.gz"
