#!/bin/sh
# Native ownership/failure check plus real first-value compatibility in both APIs.
set -eu
cd "$(dirname "$0")/.."
T=$(mktemp -d /tmp/signet-request-fields.XXXXXX)
trap 'rm -rf "$T"' 0
trap 'exit 1' HUP INT TERM
CC=${CC:-cc}
"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o"
"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    -Isrc -Ivendor -include test/http-fields-alloc.h -c src/http.c -o "$T/http.o"
"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    -Isrc -Ivendor test/http-fields.c "$T/http.o" src/conf.c src/util.c \
    "$T/sha256.o" -lkcgi -lz -o "$T/http-fields"
"$T/http-fields"
"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    -Isrc -Ivendor -I/usr/include/postgresql test/db-cache.c src/db.c src/conf.c src/util.c \
    "$T/sha256.o" -lpq -lhiredis -o "$T/db-cache"
printf '%s\n' 'db.conninfo = dbname=signet host=/run/postgresql user=signet' > "$T/db.conf"
"$T/db-cache" "$T/db.conf"
B=http://localhost:8080
ORG=request_fields_$$
curl --max-time 20 -fsS -H 'Remote-User: root' -H 'Remote-Groups: signet-admins' \
    -H 'X-Requested-With: signet' -F "org=$ORG" -F key=first -F key=second \
    -F type=text -F value=original -F value=duplicate -F unused=ignored \
    "$B/pim-api/attrs" > /dev/null
curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \
    "$B/api/pim" > "$T/pim"
jq -e --arg org "$ORG" '.[$org].text.first == "original" and .[$org].text.second == null' "$T/pim" > /dev/null
code=$(curl --max-time 20 -sS -o "$T/invalid" -w '%{http_code}' \
    -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' \
    -F file=@test/fixtures/letter.pdf -F file=@test/fixtures/seal.png \
    -F total_size=broken -F total_size=1 "$B/api/docs")
[ "$code" = 400 ] || {
    echo "FAIL - duplicate total_size HTTP $code, expected400" >&2
    exit 1
}
curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \
    -H 'X-Requested-With: signet' -F file=@test/fixtures/letter.pdf \
    -F file=@test/fixtures/seal.png -F unused=ignored "$B/api/docs" > "$T/doc"
ID=$(jq -er .id "$T/doc")
curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \
    "$B/api/docs/$ID/file/source" > "$T/source.pdf"
cmp test/fixtures/letter.pdf "$T/source.pdf"
echo 'request fields HTTP: both APIs keep first duplicate values and exact uploaded PDF'
