#!/bin/sh
# Opt-in disposable diagnostic, never for preserved/shared/production stacks.
set -eu
[ "${SIGNET_RESOURCE_PROBE_DISPOSABLE:-}" = yes ] || exit 2
T=$(mktemp -d /tmp/resource-parser.XXXXXX)
S=; PIDS=
cleanup() {
 for p in $PIDS; do kill "$p" 2>/dev/null || true; done
 if [ -n "$S" ]; then kill -TERM "$S" 2>/dev/null || true; wait "$S" 2>/dev/null || true; fi
 rm -rf "$T"
}
trap cleanup EXIT
cc -std=c99 -Wall -Wextra -O2 /src/test/resource-rss.c -o "$T/rss"
"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" --once | awk -F= '{print "baseline_app_rss_kib=" $2}'
: > "$T/peak"
"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & S=$!
for n in $(seq 1 100); do grep -q '^sampler_ready=1' "$T/peak" && break; sleep .01; done
grep -q '^sampler_ready=1' "$T/peak"
QUERY=$(awk 'BEGIN {for(i=0;i<1000;i++) printf "x=&"}')
COOKIE=$(awk 'BEGIN {for(i=0;i<1000;i++) printf "x=;"}')
phase() {
 name=$1; ct=$2; want=$3
 echo "phase=$name; body_bytes=$(wc -c < "$T/body")"
 for n in 1 2 3; do
  endpoint=api; [ "$n" != 3 ] || endpoint=pim-api
  (
   code=$(curl --max-time 30 -sS -o "$T/reply.$n" -w '%{http_code}' -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -H "Content-Type: $ct" -H "Cookie: $COOKIE" --data-binary "@$T/body" "http://localhost:8080/$endpoint/parser-probe?$QUERY")
   [ "$code" = "$want" ] || { echo "FAIL - $name HTTP $code expected $want" >&2; exit 1; }
  ) & PIDS="$PIDS $!"
 done
 for p in $PIDS; do wait "$p"; done; PIDS=
}
awk 'BEGIN {for(i=0;i<300000;i++) printf "x=&"}' > "$T/body"
phase rejected_dense_url application/x-www-form-urlencoded 413
awk 'BEGIN {for(i=0;i<225000;i++) printf "x=\r\n"}' > "$T/body"
phase rejected_dense_text text/plain 413
# Exact16KiB accepted dense forms, not only rejected large requests.
awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x"}' > "$T/body"
phase accepted_dense_url application/x-www-form-urlencoded 404
# Short nested MIME parts inherit the outer name: denser than normal FormData.
{
 printf '%s\r\n' '--z' 'Content-Disposition:a;name=x' 'Content-Type:multipart/mixed;boundary=y' ''
 awk 'BEGIN {for(i=0;i<35000;i++) printf "--y\r\nContent-Disposition:a\r\n\r\n\r\n";printf "--y--\r\n"}'
 printf '%s\r\n' '--z--'
} > "$T/body"
phase accepted_dense_nested_multipart 'multipart/form-data; boundary=z' 404
kill -TERM "$S"; wait "$S"; S=
awk '{print}' "$T/peak"
peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak")
[ -n "$peak" ] && [ "$peak" -gt 0 ] && [ "$((peak * 1024))" -lt 60000000 ] || { echo 'FAIL - parser fixture exceeds60MB aggregate application RSS'; exit 1; }
echo 'budget_result=within_for_parser_fixture; mixed-render/native gate remains OPEN'
