#!/bin/sh
# Destructive isolated-dev check: real API requests and a temporary LOCAL0 sink.
set -eu
[ "${SIGNET_LOGGING_TEST_DISPOSABLE:-}" = yes ] || {
    echo 'refusing: set SIGNET_LOGGING_TEST_DISPOSABLE=yes on a disposable stack' >&2
    exit 2
}
cd /src
umask 077
T=$(mktemp -d /tmp/signet-logging.XXXXXX)
ACTOR=lc_$$
SECRET=LOG_PRIVATE_$$
ORG=lc_org_$$
NAME=lc_fail_$$
SAVED=lc_saved_$$
SYSLOG=; SOCKET_OWNED=no; SQL_SETUP=no; REDIS_POISON=no; REDIS_SAVED=no
sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; }
cleanup() {
    if [ "$SQL_SETUP" = yes ]; then
        sql -c "DROP TRIGGER IF EXISTS $NAME ON pim_attributes; DROP TRIGGER IF EXISTS $NAME ON series; DROP FUNCTION IF EXISTS $NAME();" >/dev/null 2>&1 || true
    fi
    if [ "$REDIS_POISON" = yes ]; then
        redis-cli DEL pim:orgs >/dev/null 2>&1 || true
        [ "$REDIS_SAVED" = no ] || redis-cli RENAME "$SAVED" pim:orgs >/dev/null 2>&1 || true
    fi
    if [ -n "$SYSLOG" ]; then
        kill -TERM "$SYSLOG" 2>/dev/null || true
        wait "$SYSLOG" 2>/dev/null || true
    fi
    [ "$SOCKET_OWNED" = no ] || rm -f /dev/log
    rm -rf "$T"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM
[ ! -e /dev/log ] && [ ! -L /dev/log ] || {
    echo 'FAIL - refusing to replace an existing syslog socket' >&2; exit 1;
}
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 test/log-request.c src/util.c "$T/sha256.o" -o "$T/log-request"
"$T/log-request" 2> "$T/unit-stderr"
[ "$(wc -l < "$T/unit-stderr" | tr -d ' ')" = 4 ]
! grep -qE 'LOG_PRIVATE|success|fake|token=' "$T/unit-stderr"
grep -F 'route=/docs/:other/file/proof actor=anonymous status=400 site=fixture:1' "$T/unit-stderr" >/dev/null
grep -F 'route=/docs/:id/save actor=valid-user status=409 site=fixture:4' "$T/unit-stderr" >/dev/null
printf 'local0.warn\t%s\n' "$T/local0" > "$T/syslog.conf"
syslogd -n -O /dev/null -s 0 -f "$T/syslog.conf" > "$T/syslogd" 2>&1 &
SYSLOG=$!
tries=0
while [ ! -S /dev/log ] && [ "$tries" -lt 5 ]; do
    kill -0 "$SYSLOG"
    tries=$((tries + 1))
    sleep 1
done
[ -S /dev/log ] || { echo 'FAIL - syslog socket unavailable' >&2; exit 1; }
SOCKET_OWNED=yes
logger -p user.err "$SECRET-facility"
logger -p local0.info "$SECRET-priority"
for binary in signet-api pim-api; do
    if SIGNET_CONF="$T/$SECRET-config" "/usr/local/libexec/$binary" 2> "$T/startup"; then
        echo 'FAIL - API accepted missing configuration' >&2; exit 1
    fi
    grep -F 'cannot read configuration' "$T/startup" >/dev/null
done
request() {
    want=$1; app=$2; method=$3; route=$4; actor=$5; path=$6; shift 6
    if [ "$actor" != anonymous ]; then set -- -H "Remote-User: $actor" "$@"; fi
    code=$(curl --max-time 20 -sS -o "$T/response" -w '%{http_code}' \
        -X "$method" "$@" "http://127.0.0.1:8080/$path")
    [ "$code" = "$want" ] || { echo "FAIL - $app $method status=$code expected=$want" >&2; exit 1; }
    match="request method=$method route=$route actor=$actor status=$want site="
    tries=0
    while [ "$tries" -lt 5 ]; do
        if [ -f "$T/local0" ] && grep -F "$app[" "$T/local0" > "$T/component" &&
            grep -F "$match" "$T/component" > "$T/matched"; then break; fi
        tries=$((tries + 1))
        sleep 1
    done
    [ -f "$T/matched" ] && [ "$(wc -l < "$T/matched" | tr -d ' ')" = 1 ] &&
        grep -F "$app[" "$T/matched" >/dev/null &&
        grep -E 'site=[A-Za-z_][A-Za-z0-9_]*:[0-9]+$' "$T/matched" >/dev/null || {
        echo "FAIL - missing/duplicate/unsafe LOCAL0 record: $app $method $route status=$want" >&2; exit 1;
    }
    printf 'expect_request=%s|%s|%s|%s|%s\n' "$app" "$method" "$route" "$actor" "$want"
}
request 400 signet-api POST /docs "${ACTOR}_doc" api/docs \
    -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -d "unused=$SECRET-body"
request 400 pim-api POST /attrs "${ACTOR}_pim" pim-api/attrs \
    -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "org=$ORG&value=$SECRET-value"
request 404 signet-api GET /:other "${ACTOR}_path" "api/$SECRET-path?token=$SECRET-query" \
    -H "Authorization: Bearer $SECRET-token" -H "Cookie: credential=$SECRET-cookie"
request 404 signet-api GET /docs/:id/file/proof "${ACTOR}_file" \
    api/docs/00000000-0000-0000-0000-000000000000/file/proof
request 401 signet-api GET /me anonymous api/me -H 'Remote-User:'
request 401 pim-api GET /me anonymous pim-api/me -H "Remote-User: $SECRET/invalid"
request 403 signet-api POST /docs "${ACTOR}_csrf" api/docs -H 'Remote-Groups: clerks' -d ''
request 403 pim-api POST /attrs "${ACTOR}_role" pim-api/attrs \
    -H 'Remote-Groups: unknown' -H 'X-Requested-With: signet' -d ''
# Backend messages/DETAIL may repeat submitted values; log only SQLSTATE.
SQL_SETUP=yes
sql -c "CREATE FUNCTION $NAME() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF TG_TABLE_NAME='series' THEN RAISE EXCEPTION '$SECRET-db' USING DETAIL='$SECRET-detail', ERRCODE='23505'; ELSE RAISE EXCEPTION '$SECRET-db' USING DETAIL='$SECRET-detail'; END IF; END \$\$; CREATE TRIGGER $NAME BEFORE INSERT ON series FOR EACH ROW WHEN (NEW.code='$SECRET') EXECUTE FUNCTION $NAME(); CREATE TRIGGER $NAME BEFORE INSERT ON pim_attributes FOR EACH ROW WHEN (NEW.org_code='$ORG') EXECUTE FUNCTION $NAME();" >/dev/null
request 500 signet-api POST /series "${ACTOR}_sql" api/series \
    -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "code=$SECRET&pattern=TEST/{seq:02}"
request 500 pim-api POST /attrs "${ACTOR}_sql" pim-api/attrs \
    -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "org=$ORG&key=test&type=text&value=$SECRET-value"
[ "$(redis-cli EXISTS "$SAVED")" = 0 ] || { echo 'FAIL - Redis backup key exists' >&2; exit 1; }
if [ "$(redis-cli EXISTS pim:orgs)" = 1 ]; then
    redis-cli RENAME pim:orgs "$SAVED" >/dev/null
    REDIS_SAVED=yes
fi
REDIS_POISON=yes
redis-cli SET pim:orgs "$SECRET-redis" >/dev/null
request 503 pim-api POST /resync "${ACTOR}_redis" pim-api/resync \
    -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d ''
for app in api pim-api; do
    curl --max-time 20 -fsS -H "Remote-User: ${ACTOR}_ok" -H 'Remote-Groups: clerks' \
        "http://127.0.0.1:8080/$app/me" > /dev/null
done
sleep 1
! grep -qF "$SECRET" "$T/local0" || { echo 'FAIL - private data or excluded syslog facility/priority leaked' >&2; exit 1; }
! grep -qF "actor=${ACTOR}_ok " "$T/local0" || { echo 'FAIL - successful requests logged as failures' >&2; exit 1; }
grep -F 'SQLSTATE 23505' "$T/local0" > /dev/null
grep -F 'SQLSTATE P0001' "$T/local0" > /dev/null
kill -TERM "$SYSLOG"
wait "$SYSLOG" 2>/dev/null || true
SYSLOG=
rm -f /dev/log
SOCKET_OWNED=no
# The host-side check must see stderr records even without a syslog receiver.
for endpoint in api/docs pim-api/attrs; do
    case "$endpoint" in api/docs) app=signet-api; route=/docs;; *) app=pim-api; route=/attrs;; esac
    code=$(curl --max-time 20 -sS -o "$T/response" -w '%{http_code}' \
        -H "Remote-User: ${ACTOR}_fallback" -H 'Remote-Groups: clerks,signet-admins' \
        -H 'X-Requested-With: signet' -d '' "http://127.0.0.1:8080/$endpoint")
    [ "$code" = 400 ]
    printf 'expect_request=%s|POST|%s|%s_fallback|400\n' "$app" "$route" "$ACTOR"
done
printf 'logging_private_marker=%s\n' "$SECRET"
printf 'logging_success_actor=%s_ok\n' "$ACTOR"
echo 'logging contract: both API handler/auth/file/SQL/Redis failures, LOCAL0 filtering, privacy and success silence passed'
