#!/bin/sh
# Local synthetic HTTPS TSA only. Never run against preserved/shared services.
set -eu
[ "${SIGNET_TIMESTAMP_TEST_DISPOSABLE:-}" = yes ] || exit 2
cd /src
T=$(mktemp -d /tmp/signet-timestamp.XXXXXX)
SERVER=; HOLDER=; CRON=; RUNNER=; SAMPLER=; RENAMED=; API_CONFIGURED=
cleanup() {
    if [ -n "$API_CONFIGURED" ]; then restart_api /etc/signet/signet.conf || true; fi
    if [ -n "$RENAMED" ]; then sql -c 'ALTER TABLE document_timestamps RENAME COLUMN fixture_response TO response' > /dev/null 2>&1 || true; fi
    if [ -n "$SAMPLER" ]; then kill "$SAMPLER" 2>/dev/null || true; wait "$SAMPLER" 2>/dev/null || true; fi
    if [ -n "$RUNNER" ]; then kill "$RUNNER" 2>/dev/null || true; wait "$RUNNER" 2>/dev/null || true; fi
    if [ -n "$CRON" ]; then kill "$CRON" 2>/dev/null || true; wait "$CRON" 2>/dev/null || true; fi
    pkill -f "^/usr/local/libexec/signet-timestamp -c $T/worker[.]conf$" 2>/dev/null || true
    if [ -n "$HOLDER" ]; then
        sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='timestamp_holder_$$'" > /dev/null 2>&1 || true
        wait "$HOLDER" 2>/dev/null || true
    fi
    if [ -n "$SERVER" ]; then kill "$SERVER" 2>/dev/null || true; wait "$SERVER" 2>/dev/null || true; fi
    rm -rf "$T"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM
chmod 755 "$T"
if [ "${SIGNET_TIMESTAMP_TEST_RSS:-no}" = yes ]; then
    cc -std=c99 -O2 -Wall -Wextra test/resource-rss.c -o "$T/rss"
    : > "$T/rss.log"
    "$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/rss.log" &
    SAMPLER=$!; n=0
    while ! grep -q '^sampler_ready=1$' "$T/rss.log"; do
        kill -0 "$SAMPLER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .01
    done
fi
sh /src/test/timestamp-migration.sh
cc -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    test/timestamp-fixture.c -lssl -lcrypto -o "$T/fixture"
cc -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra -Isrc \
    $(pkg-config --cflags libcurl libcrypto) test/timestamp-client.c src/timestamp.c \
    $(pkg-config --libs libcurl libcrypto) -o "$T/client"
"$T/fixture" "$T" > "$T/server.log" 2>&1 &
SERVER=$!; n=0
while [ ! -f "$T/port" ]; do
    kill -0 "$SERVER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
done
port=$(tr -d '\n' < "$T/port")
URL=https://127.0.0.1:$port
"$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" good 3000
for mode in good384 good512; do
    printf '%s\n' "$mode" > "$T/mode"
    "$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" good 3000
done
for mode in nonce imprint signature malformed oversize http expired weak rejected; do
    printf '%s\n' "$mode" > "$T/mode"
    "$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" "$mode" 3000
done
printf '%s\n' good > "$T/mode"
"$T/client" "$URL" "$T/other.pem" "$T/ca.pem" untrusted_tsa 3000
"$T/client" "$URL" "$T/ca.pem" "$T/other.pem" untrusted_https 3000
"$T/client" "http://127.0.0.1:$port" "$T/ca.pem" "$T/ca.pem" non_https 3000
printf '%s\n' slow > "$T/mode"
"$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" timeout 200
sleep 2
printf '%s\n' good > "$T/mode"
# Existing tests may have released synthetic documents; keep this fixture's
# network work scoped to the new document. This is why opt-in is mandatory.
sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; }
sql -f sql/migrations/004-detached-timestamps.sql > /dev/null
sql -f sql/migrations/004-detached-timestamps.sql > /dev/null
sql -c "UPDATE document_timestamps SET state='unavailable',next_attempt_at=NULL WHERE state='pending';
 INSERT INTO document_timestamps (doc_id,revision,pdf_sha256,state,started_at,deadline)
 SELECT id,revision,final_sha256,'unavailable',released_at,released_at+interval '1 hour'
 FROM documents WHERE status='RELEASED' ON CONFLICT (doc_id) DO NOTHING" > /dev/null
awk '!/^timestamp\./' /etc/signet/signet.conf > "$T/worker.conf"
printf 'timestamp.url = %s\ntimestamp.ca_file = %s/ca.pem\ntimestamp.tls_ca_file = %s/ca.pem\n' "$URL" "$T" "$T" >> "$T/worker.conf"
chmod 644 "$T/worker.conf" "$T/ca.pem"
run_worker() { su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf"; }
restart_api() {
    pkill -f '^kfcgi .* /run/signet/api.sock' 2>/dev/null || true
    pkill -f '^/usr/local/libexec/signet-api' 2>/dev/null || true
    tries=0
    while pgrep -f '^kfcgi .* /run/signet/api.sock|^/usr/local/libexec/signet-api' > /dev/null; do
        tries=$((tries + 1)); [ "$tries" -lt 100 ]; sleep .05
    done
    rm -f /run/signet/api.sock
    SIGNET_CONF="$1" kfcgi -d -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- \
        /usr/local/libexec/signet-api >> /proc/1/fd/2 2>&1 &
    api_pid=$!; tries=0
    while [ ! -S /run/signet/api.sock ] || ! curl --max-time 2 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' http://localhost:8080/api/me > /dev/null 2>&1; do
        kill -0 "$api_pid"; tries=$((tries + 1)); [ "$tries" -lt 100 ]; sleep .05
    done
}
B=http://localhost:8080
request() {
    user=$1; groups=$2; shift 2
    curl --max-time 30 -fsS -H "Remote-User: $user" -H "Remote-Groups: $groups" \
        -H 'X-Requested-With: signet' "$@"
}
ORG=timestamp_test_$$
request root signet-admins -F "org=$ORG" -F key=reference -F type=text -F value=synthetic "$B/pim-api/attrs" > /dev/null
request asha clerks -F file=@test/fixtures/letter.pdf "$B/api/docs" > "$T/created"
ID=$(jq -er .id "$T/created")
jq -nc --arg org "$ORG" '{title:"Synthetic detached timestamp",org_code:$org,
    route:{parties:[{name:"Manager",signer:"manager"}]},
    layout:{reference_width:1000,reference_height:1414,imprints:[]}}' > "$T/layout"
request asha clerks -F "json=<$T/layout" "$B/api/docs/$ID/save" > /dev/null
request asha clerks -d '' "$B/api/docs/$ID/submit" > /dev/null
wait_ready() {
    n=0
    while :; do
        request asha clerks "$B/api/docs/$ID" > "$T/doc"
        jq -e '.render_error == null' "$T/doc" > /dev/null
        if jq -e '.rendered_seq == .render_seq' "$T/doc" > /dev/null; then return; fi
        n=$((n + 1)); [ "$n" -lt 200 ]; sleep .05
    done
}
wait_ready
request manager management -F decision=signoff "$B/api/docs/$ID/decide" > /dev/null
wait_ready
jq -e '.status == "RELEASED" and .signed_at != null and .timestamped_at == null' "$T/doc" > /dev/null
SHA=$(jq -er .final_sha256 "$T/doc")
SIGNED=$(jq -er .signed_at "$T/doc")
jq -e '.timestamp_status == "not_requested" and .timestamp_attempts == 0' "$T/doc" > /dev/null
API_CONFIGURED=yes
restart_api "$T/worker.conf"
request asha clerks "$B/api/docs/$ID" > "$T/doc"
jq -e '.timestamp_status == "pending" and .timestamped_at == null' "$T/doc" > /dev/null
# A concurrent runner cannot claim an attempt while the session lock is held.
su-exec postgres env PGAPPNAME="timestamp_holder_$$" psql -X -q -d signet \
    -c 'SELECT pg_advisory_lock(1936289381,1953721965); SELECT pg_sleep(30)' > "$T/holder" 2>&1 &
HOLDER=$!; n=0
while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 1 ]; do
    n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
done
count=$(tr -d '\n' < "$T/requests")
run_worker
[ "$(tr -d '\n' < "$T/requests")" = "$count" ]
sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='timestamp_holder_$$'" > /dev/null
wait "$HOLDER" 2>/dev/null || true
HOLDER=
# HTTP failure must not alter the final PDF, release, or recorded sign-off time.
printf '%s\n' http > "$T/mode"
for attempt in 1 2 3 4; do
    if [ "$attempt" -gt 1 ]; then
        sql -c "UPDATE document_timestamps SET next_attempt_at=clock_timestamp()-interval '1 second' WHERE doc_id='$ID'" > /dev/null
    fi
    run_worker
    [ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = "$attempt" ]
    if [ "$attempt" = 1 ]; then
        [ "$(sql -c "SELECT next_attempt_at=started_at+interval '5 minutes' FROM document_timestamps WHERE doc_id='$ID'")" = t ]
    fi
done
[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = unavailable ]
request asha clerks "$B/api/docs/$ID" > "$T/doc"
jq -e --arg signed "$SIGNED" '.status == "RELEASED" and .signed_at == $signed and .timestamp_status == "unavailable" and .timestamped_at == null' "$T/doc" > /dev/null
count=$(tr -d '\n' < "$T/requests")
run_worker
[ "$(tr -d '\n' < "$T/requests")" = "$count" ]
# A crash after claim/request consumes its slot; restarting cannot reclaim it.
sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null
rm -f "$T/holding" "$T/release"
printf '%s\n' hold > "$T/mode"
su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf" > "$T/crashed" 2>&1 &
RUNNER=$!; n=0
while [ ! -f "$T/holding" ]; do
    kill -0 "$RUNNER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
done
[ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = 1 ]
kill -KILL "$RUNNER"; wait "$RUNNER" 2>/dev/null || true; RUNNER=
: > "$T/release"
n=0
while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 0 ]; do
    n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
done
count=$(tr -d '\n' < "$T/requests")
run_worker
[ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = 1 ]
[ "$(tr -d '\n' < "$T/requests")" = "$count" ]
# A missed window expires without another request, even after process restart.
sql -c "UPDATE document_timestamps SET state='pending',attempts=1,started_at=CURRENT_TIMESTAMP-interval '2 hours',
 deadline=CURRENT_TIMESTAMP-interval '1 hour',next_attempt_at=clock_timestamp()-interval '1 hour' WHERE doc_id='$ID'" > /dev/null
run_worker
[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = unavailable ]
[ "$(tr -d '\n' < "$T/requests")" = "$count" ]
# Reset only this synthetic fixture's evidence to exercise successful validation.
sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null
printf '%s\n' good > "$T/mode"
run_worker
request asha clerks "$B/api/docs/$ID" > "$T/doc"
jq -e --arg sha "$SHA" --arg signed "$SIGNED" '.status == "RELEASED" and .final_sha256 == $sha and .signed_at == $signed and .timestamp_status == "timestamped" and .timestamped_at != null and .timestamp_attempts == 1' "$T/doc" > /dev/null
request asha clerks "$B/api/docs/$ID/file/final" > "$T/final.pdf"
[ "$(sha256sum "$T/final.pdf" | cut -d ' ' -f 1)" = "$SHA" ]
request asha clerks "$B/api/docs/$ID/file/timestamp" > "$T/download.tsr"
cmp "$T/download.tsr" "$T/response.der"
request manager management "$B/api/docs/$ID/file/timestamp" > "$T/party.tsr"
cmp "$T/download.tsr" "$T/party.tsr"
request root signet-admins "$B/api/docs/$ID/file/timestamp" > "$T/admin.tsr"
cmp "$T/download.tsr" "$T/admin.tsr"
# Backend failure is temporarily unavailable, not a false missing-evidence claim.
sql -c 'ALTER TABLE document_timestamps RENAME COLUMN response TO fixture_response' > /dev/null
RENAMED=yes
code=$(curl --max-time 10 -sS -o "$T/backend" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp")
[ "$code" = 503 ]
sql -c 'ALTER TABLE document_timestamps RENAME COLUMN fixture_response TO response' > /dev/null
RENAMED=
# Even a valid stored response must match the released revision AND hash.
sql -c "UPDATE document_timestamps SET revision=revision+1 WHERE doc_id='$ID'" > /dev/null
code=$(curl --max-time 10 -sS -o "$T/stale" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp")
[ "$code" = 404 ]
sql -c "UPDATE document_timestamps SET revision=revision-1,pdf_sha256=repeat('b',64) WHERE doc_id='$ID'" > /dev/null
code=$(curl --max-time 10 -sS -o "$T/stale" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp")
[ "$code" = 404 ]
request asha clerks "$B/api/docs/$ID" > "$T/stale-meta"
jq -e '.timestamped_at == null and .timestamp_status != "timestamped"' "$T/stale-meta" > /dev/null
sql -c "UPDATE document_timestamps SET pdf_sha256='$SHA' WHERE doc_id='$ID'" > /dev/null
code=$(curl --max-time 10 -sS -o "$T/denied" -w '%{http_code}' -H 'Remote-User: unrelated' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp")
[ "$code" = 404 ]
count=$(tr -d '\n' < "$T/requests")
run_worker
[ "$(tr -d '\n' < "$T/requests")" = "$count" ]
if sql -c "UPDATE document_timestamps SET attempts=5 WHERE doc_id='$ID'" > "$T/constraint" 2>&1; then exit 1; fi
if sql -c "UPDATE document_timestamps SET response=repeat('x',65537)::bytea WHERE doc_id='$ID'" > "$T/constraint" 2>&1; then exit 1; fi
# Hold a real TSA request while a different document signs and releases.
sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null
rm -f "$T/holding" "$T/release"
printf '%s\n' hold > "$T/mode"
su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf" > "$T/background" 2>&1 &
RUNNER=$!; n=0
while [ ! -f "$T/holding" ]; do
    kill -0 "$RUNNER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
done
ORIGINAL=$ID
request asha clerks -F file=@test/fixtures/letter.pdf "$B/api/docs" > "$T/second"
ID=$(jq -er .id "$T/second")
request asha clerks -F "json=<$T/layout" "$B/api/docs/$ID/save" > /dev/null
request asha clerks -d '' "$B/api/docs/$ID/submit" > /dev/null
wait_ready
request manager management -F decision=signoff "$B/api/docs/$ID/decide" > /dev/null
wait_ready
jq -e '.status == "RELEASED"' "$T/doc" > /dev/null
kill -0 "$RUNNER"
[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ORIGINAL'")" = pending ]
: > "$T/release"
wait "$RUNNER"; RUNNER=
ID=$ORIGINAL
[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = timestamped ]
printf '%s\n' good > "$T/mode"
echo 'timestamp independence: another document released while HTTPS request was held'
# Optional real scheduler acceptance; does not change the host/VM clock.
if [ "${SIGNET_TIMESTAMP_TEST_CRON:-no}" = yes ]; then
    sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null
    mkdir "$T/crontabs"
    printf '* * * * * /usr/local/libexec/signet-timestamp -c %s/worker.conf\n' "$T" > "$T/crontabs/signetd"
    crond -f -c "$T/crontabs" -l 8 > "$T/cron.log" 2>&1 &
    CRON=$!; n=0
    while [ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" != timestamped ]; do
        kill -0 "$CRON"; n=$((n + 1)); [ "$n" -lt 75 ]; sleep 1
    done
    n=0
    while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 0 ]; do
        n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05
    done
    kill "$CRON"; wait "$CRON" 2>/dev/null || true; CRON=
    echo 'timestamp cron: real scheduled invocation passed'
fi
# Normal document status/event history is never replaced by timestamp outcomes.
[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='RELEASED'")" = 1 ]
restart_api /etc/signet/signet.conf
API_CONFIGURED=
request asha clerks "$B/api/docs/$ID" > "$T/doc"
jq -e '.timestamp_status == "timestamped" and .timestamped_at != null' "$T/doc" > /dev/null
if [ -n "$SAMPLER" ]; then
    kill "$SAMPLER"; wait "$SAMPLER"; SAMPLER=
    peak=$(awk -F= '/^transient_sampled_app_peak_kib=/{print $2}' "$T/rss.log")
    [ -n "$peak" ] && [ "$((peak * 1024))" -lt 60000000 ]
    printf 'timestamp_contract_sampled_app_peak_kib=%s\n' "$peak"
fi
echo 'timestamp contract: nonce/imprint/signature/trust/TLS/size/status/timeouts, bounded retries, expiry, immutable PDF, separate times and authorized evidence passed'
