#!/bin/sh
# Run where the existing podman CLI works, against an explicitly disposable stack.
set -eu
[ "${SIGNET_LOGGING_TEST_DISPOSABLE:-}" = yes ] && [ "$#" = 1 ] || {
    echo 'usage: SIGNET_LOGGING_TEST_DISPOSABLE=yes sh test/logging-dev.sh disposable-container' >&2
    exit 2
}
umask 077
T=$(mktemp -d /tmp/signet-logging-dev.XXXXXX)
trap 'rm -rf "$T"' 0
trap 'exit 1' HUP INT TERM
podman logs "$1" > "$T/before" 2>&1
before=$(wc -l < "$T/before")
podman exec -e SIGNET_LOGGING_TEST_DISPOSABLE=yes "$1" sh /src/test/logging-contract.sh > "$T/probe"
sleep 1
podman logs "$1" > "$T/all" 2>&1
awk -v before="$before" 'NR > before' "$T/all" > "$T/capture"
while IFS='|' read -r app method route actor status; do
    match="request method=$method route=$route actor=$actor status=$status site="
    grep -F "$match" "$T/capture" > "$T/component" &&
        grep -E "^$app\\[[0-9]+\\]: " "$T/component" > "$T/matched" || {
        echo "FAIL - real container capture missing $app $method $route status=$status" >&2; exit 1;
    }
    [ "$(wc -l < "$T/matched" | tr -d ' ')" = 1 ] || {
        echo 'FAIL - duplicate request failure records in real capture' >&2; exit 1;
    }
done <<EOF
$(awk -F= '/^expect_request=/ {print $2}' "$T/probe")
EOF
marker=$(awk -F= '/^logging_private_marker=/ {print $2}' "$T/probe")
success=$(awk -F= '/^logging_success_actor=/ {print $2}' "$T/probe")
[ -n "$marker" ] && [ -n "$success" ]
! grep -qF "$marker" "$T/capture" || { echo 'FAIL - private data in real container capture' >&2; exit 1; }
! grep -qF "actor=$success " "$T/capture" || { echo 'FAIL - success logged as failure' >&2; exit 1; }
cat "$T/probe"
echo 'logging dev capture: real podman logs contains both API failure records without private values'
