#!/usr/bin/env bash
# Standalone RFC 3161 verifier. Bash 3.2+, OpenSSL 3.x; no application code.
# A CRLF copy cannot parse as shell code. This first command also works with
# a trailing CR and gives an actionable error before the remaining lines parse.
case $(head -n 1 "$0" 2>/dev/null) in *$'\r'*) printf '%s\n' '[FAIL] CRLF script: save as LF, or run: sed "s/\r$//" stampr-verify.sh > stampr-verify-lf.sh; bash stampr-verify-lf.sh ...' >&2; exit 2 ;; esac #

set -u
set -o pipefail
export LC_ALL=C
# Direct connections only, including OpenSSL's HTTP client.
unset http_proxy HTTP_PROXY https_proxy HTTPS_PROXY all_proxy ALL_PROXY
umask 077
VERSION=1.0.1
ROOT_PIN=D33895E1D51123F948C8C999F7F72640FA0505FBD15AB093E898DB27DD2914E8
ROOT_URL=https://ca.b-trust.org/repository/B-TrustRootQCA.cer
OPER_URL=https://ca.b-trust.org/repository/B-TrustOperationalQCA.cer
OCSP_URL=http://ocsp.b-trust.org
CRL_URL=http://crl.b-trust.org/repository/B-TrustOperationalQCA.crl
TL_URL=https://crc.bg/files/_en/TSL_BG.xml

usage() {
    cat <<'EOF'
stampr-verify.sh 1.0.1 — independent B-Trust RFC 3161 verification
Usage: bash stampr-verify.sh (--tsr FILE | --pdf FILE)
       (--file FILE | --hash HEX64 | both) [options]
  --serial 0xHEX                  Certificate's token serial
  --time "YYYY-MM-DD HH:MM:SS"     Certificate's Sofia wall-clock time
  --certs-dir DIR                 Local B-Trust root and operational certs
  --offline                       No network; requires --certs-dir
  --ocsp-file FILE                 Archived DER OCSP response
  --out FILE                      UTF-8 report (default in current directory)
  --help                          Show this help
PDF extraction requires pdfdetach. Otherwise save the attached .tsr using
Adobe Acrobat Reader's Attachments panel and rerun with --tsr.
EOF
}

detect_date() {
    if date -u -d 'Nov  3 09:40:12 2026 GMT' +%s >/dev/null 2>&1; then
        DATE_KIND=GNU
    elif date -j -u -f '%b %e %T %Y %Z' 'Nov  3 09:40:12 2026 GMT' +%s >/dev/null 2>&1; then
        DATE_KIND=BSD
    else
        return 1
    fi
}

# RFC 3161 text can contain fractional seconds and space-padded days.
# Integer epoch is the start of that second; retain the original text in reports.
epoch() {
    local value
    value=$(printf '%s\n' "$1" | sed 's/\([0-9][0-9]:[0-9][0-9]:[0-9][0-9]\)\.[0-9][0-9]*/\1/')
    if [ "$DATE_KIND" = GNU ]; then
        date -u -d "$value" +%s 2>/dev/null
    elif printf '%s' "$value" | grep -Eq '^[0-9]{4}-'; then
        date -j -u -f '%Y-%m-%dT%H:%M:%SZ' "$value" +%s 2>/dev/null
    else
        date -j -u -f '%b %e %T %Y %Z' "$value" +%s 2>/dev/null
    fi
}

format_epoch() {
    if [ "$DATE_KIND" = GNU ]; then
        TZ="$2" date -d "@$1" "+$3"
    else
        TZ="$2" date -r "$1" "+$3"
    fi
}

# Bulgaria has followed the EU rule since 1997: transitions at 01:00 UTC
# on the last Sundays of March and October. No zoneinfo files are needed.
sofia_time() {
    local instant=$1 year march october weekday
    year=$(format_epoch "$instant" UTC '%Y') || return 1
    [ "$year" -ge 1997 ] || return 1
    march=$(epoch "$year-03-31T01:00:00Z") || return 1
    october=$(epoch "$year-10-31T01:00:00Z") || return 1
    weekday=$(format_epoch "$march" UTC '%w') || return 1
    march=$((march - weekday * 86400))
    weekday=$(format_epoch "$october" UTC '%w') || return 1
    october=$((october - weekday * 86400))
    if [ "$instant" -ge "$march" ] && [ "$instant" -lt "$october" ]; then
        offset=+0300
        sofia=$(format_epoch "$((instant + 10800))" UTC '%Y-%m-%d %H:%M:%S')
    else
        offset=+0200
        sofia=$(format_epoch "$((instant + 7200))" UTC '%Y-%m-%d %H:%M:%S')
    fi
}

if [ "${1-}" = --self-test-sofia ] && [ "$#" -eq 2 ]; then
    detect_date && sofia_time "$2" && printf '%s|%s\n' "$sofia" "$offset"
    exit $?
fi

if [ "${1-}" = --self-test-epoch ] && [ "$#" -eq 2 ]; then
    detect_date && epoch "$2"
    exit $?
fi

tsr= pdf= original= supplied_hash= supplied_serial= supplied_time= certs_dir= archived_ocsp= out=
offline=0
arguments=
for argument in "$@"; do
    printf -v quoted '%q' "$argument"
    arguments="$arguments $quoted"
done
bad_usage() { printf '[FAIL] Usage: %s\n' "$1" >&2; usage >&2; exit 2; }
while [ "$#" -gt 0 ]; do
    case "$1" in
        --help) usage; exit 0 ;;
        --offline) offline=1; shift ;;
        --tsr|--pdf|--file|--hash|--serial|--time|--certs-dir|--ocsp-file|--out)
            [ "$#" -ge 2 ] && [ -n "$2" ] || bad_usage "Missing value for $1"
            case "$1" in
                --tsr) [ -z "$tsr$pdf" ] || bad_usage 'Choose exactly one token source'; tsr=$2 ;;
                --pdf) [ -z "$tsr$pdf" ] || bad_usage 'Choose exactly one token source'; pdf=$2 ;;
                --file) original=$2 ;;
                --hash) supplied_hash=$2 ;;
                --serial) supplied_serial=$2 ;;
                --time) supplied_time=$2 ;;
                --certs-dir) certs_dir=$2 ;;
                --ocsp-file) archived_ocsp=$2 ;;
                --out) out=$2 ;;
            esac
            shift 2 ;;
        *) bad_usage "Unknown argument: $1" ;;
    esac
done
[ -n "$tsr$pdf" ] || bad_usage 'A --tsr or --pdf is required'
[ -n "$original$supplied_hash" ] || bad_usage 'A --file or --hash is required'
[ "$offline" -eq 0 ] || [ -n "$certs_dir" ] || bad_usage '--offline requires --certs-dir'
if [ -n "$supplied_hash" ]; then
    printf '%s\n' "$supplied_hash" | grep -Eq '^[[:xdigit:]]{64}$' || bad_usage '--hash must contain 64 hex characters'
fi
if [ -n "$supplied_serial" ]; then
    printf '%s\n' "$supplied_serial" | grep -Eq '^0[xX][[:xdigit:]]+$' || bad_usage '--serial must be 0x followed by hex'
fi
if [ -n "$supplied_time" ]; then
    printf '%s\n' "$supplied_time" | grep -Eq '^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$' || bad_usage 'Invalid --time format'
fi
for input in "$tsr" "$pdf" "$original" "$archived_ocsp"; do
    if [ -n "$input" ] && { [ ! -r "$input" ] || [ ! -f "$input" ]; }; then
        bad_usage "Input is not a readable regular file: $input"
    fi
done
for prerequisite in curl date awk sed grep tr mktemp uname tee cmp mkdir cat rm head tail; do
    command -v "$prerequisite" >/dev/null 2>&1 || { printf '[FAIL] Missing prerequisite: %s\n' "$prerequisite" >&2; exit 2; }
done
if [ -n "$pdf" ] && ! command -v pdfdetach >/dev/null 2>&1; then
    printf '[FAIL] pdfdetach is missing. Save the attached .tsr in Adobe Acrobat Reader’s Attachments panel and rerun with --tsr.\n' >&2
    exit 2
fi
detect_date || { printf '[FAIL] Need GNU date -d or BSD date -j -f.\n' >&2; exit 2; }
# Homebrew OpenSSL is keg-only; macOS PATH commonly still selects LibreSSL.
OPENSSL=
for candidate in "$(command -v openssl 2>/dev/null || true)" \
    /opt/homebrew/opt/openssl@3/bin/openssl /usr/local/opt/openssl@3/bin/openssl; do
    [ -n "$candidate" ] && [ -x "$candidate" ] || continue
    case "$("$candidate" version 2>/dev/null | tr -d '\r')" in
        'OpenSSL 3.'*) OPENSSL=$candidate; break ;;
    esac
done
if [ -z "$OPENSSL" ]; then
    printf '%s\n' '[FAIL] Requires OpenSSL 3.x (LibreSSL is unsupported). On macOS: brew install openssl@3; then export PATH="$(brew --prefix openssl@3)/bin:$PATH"' >&2
    exit 2
fi

tmp=$(mktemp -d "${TMPDIR:-/tmp}/stampr-verify.XXXXXXXX") || exit 2
trap 'rm -rf "$tmp"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
checks=$tmp/checks
appendix=$tmp/appendix
hashes=$tmp/hashes
failures=$tmp/failures
: > "$checks"; : > "$appendix"; : > "$hashes"; : > "$failures"
core_failed=0
serial=unknown
imprint=unknown
token_time=unknown
sofia=unknown
sofia_label=unknown
run_time=$(date -u '+%Y-%m-%dT%H:%M:%SZ')

check() {
    # Only pass "core" for the exit-code-defining checks.
    printf '[%s] %s\n' "$1" "$2" | tee -a "$checks"
    if [ "$1" = FAIL ]; then
        printf '%s\n' "$2" >> "$failures"
        [ "${3-}" != core ] || core_failed=1
    fi
}

ssl() {
    local destination=$1 rc
    shift
    printf '\n$ %s' "$OPENSSL" >> "$appendix"
    printf ' %q' "$@" >> "$appendix"
    printf '\n' >> "$appendix"
    "$OPENSSL" "$@" > "$destination.raw" 2>&1
    rc=$?
    cat "$destination.raw" >> "$appendix"
    # Native Windows OpenSSL emits CRLF. Normalize parsed text only; files
    # written by -out/-respout and the raw appendix remain untouched.
    tr -d '\r' < "$destination.raw" > "$destination"
    printf '\n[exit %s]\n' "$rc" >> "$appendix"
    return "$rc"
}

hash_file() {
    HASH=
    if ssl "$tmp/hash-output" dgst -sha256 -r "$2"; then
        HASH=$(awk '{print $1; exit}' "$tmp/hash-output")
        printf '%s: %s  %s\n' "$1" "$HASH" "$2" >> "$hashes"
    else
        check FAIL "Cannot hash $1" core
    fi
}

finish() {
    local code=${1:-$core_failed} verdict
    [ -n "$out" ] || out="stampr-verification-${serial}-$(date -u '+%Y%m%dT%H%M%SZ').txt"
    # Never replace an input, including an input reached through a symlink.
    for input in "$tsr" "$pdf" "$original" "$archived_ocsp" "${root-}" "${oper-}"; do
        if [ -n "$input" ] && [ "$out" -ef "$input" ]; then
            printf '[FAIL] Report path aliases an input: %s\n' "$out" >&2; exit 2
        fi
    done
    if [ "$code" -eq 0 ]; then verdict='PASS — all core checks passed (review warnings and skipped checks)'
    elif [ "$code" -eq 2 ]; then verdict='ERROR — missing prerequisite or unusable report'
    else verdict='FAIL — core verification failed'; fi
    {
        printf 'StampR independent RFC 3161 verifier %s\nRun UTC: %s\nSystem: %s\nOpenSSL: %s\nArguments:%s\n' "$VERSION" "$run_time" "$(uname -a)" "${openssl_version-unknown}" "$arguments"
        printf '\nSHA-256 of inputs and downloaded evidence\n'; cat "$hashes"
        printf '\nChecks\n'; cat "$checks"
        printf '\nAppendix: raw command output\n'; cat "$appendix"
        printf '\nOverall verdict: %s\n' "$verdict"
        if [ "$code" -eq 0 ]; then
            printf 'BG: Заключение: данните с SHA-256 хеш %s са съществували в непроменен вид не по-късно от %s (%s %s), удостоверено с квалифициран електронен времеви печат на БОРИКА АД, сериен номер %s.\n' "$imprint" "$token_time" "$sofia" "$sofia_label" "$serial"
            printf 'EN: Conclusion: the data with SHA-256 hash %s existed unchanged no later than %s (%s %s), certified by a qualified electronic timestamp of BORICA AD, serial number %s.\n' "$imprint" "$token_time" "$sofia" "$sofia_label" "$serial"
            printf 'BG: Заключението обхваща основните криптографски проверки; прегледайте предупрежденията за отмяна и историята на доверителния списък.\nEN: This conclusion covers the core cryptographic checks; review revocation and trusted-list history warnings.\n'
        else
            printf 'BG: Заключение: проверката е неуспешна; положително заключение не се прави.\nEN: Conclusion: verification failed; no positive conclusion is made.\nFailing checks:\n'
            cat "$failures"
        fi
    } > "$out" || { printf '[FAIL] Cannot write report: %s\n' "$out" >&2; exit 2; }
    printf 'Overall verdict: %s\nReport: %s\n' "$verdict" "$out"
    exit "$code"
}

# No redirects, no configuration-file URLs, and no use of unapproved cert URLs.
download() {
    local url=$1 destination=$2
    case "$url" in
        "$ROOT_URL"|"$OPER_URL"|"$CRL_URL"|"$TL_URL") ;;
        *) return 1 ;;
    esac
    curl -q --fail --silent --show-error --noproxy '*' --proto '=http,https' \
        --connect-timeout 15 --max-time 90 --output "$destination" "$url" 2> "$tmp/curl-error"
}

normalize_hex() { printf '%s' "$1" | tr '[:lower:]' '[:upper:]' | sed 's/^0X//; s/://g; s/^0*//'; }
field() { sed -n "s/^$1: *//p" "$2" | head -n 1; }

ssl "$tmp/version" version
openssl_version=$(cat "$tmp/version")
curl_version=$(curl -q --version | awk 'NR==1 {print $1, $2}')
case "$openssl_version" in
    'OpenSSL 3.'*) check PASS "1. Prerequisites: $openssl_version ($OPENSSL); $curl_version; $DATE_KIND date; Sofia EU timezone rule (1997+)" ;;
    *) check WARN "1. Requires OpenSSL 3.x; found $openssl_version. Put OpenSSL 3 first in PATH."; finish 2 ;;
esac

if [ -n "$pdf" ]; then
    hash_file 'Input PDF' "$pdf"
    mkdir "$tmp/pdf"
    if ! pdfdetach -saveall -o "$tmp/pdf" "$pdf" > "$tmp/pdf-output" 2>&1; then
        check FAIL '2. Cannot extract PDF attachments with pdfdetach' core; finish
    fi
    # pdfdetach may list one attachment twice. Accept identical copies only.
    for attachment in "$tmp/pdf/"*; do
        [ -f "$attachment" ] || continue
        case "$attachment" in *.[tT][sS][rR]) ;;
            *) continue ;;
        esac
        if [ -z "$tsr" ]; then tsr=$attachment
        elif ! cmp -s "$tsr" "$attachment"; then
            check FAIL '2. PDF contains different .tsr attachments; save the intended token and use --tsr' core; finish
        fi
    done
    [ -n "$tsr" ] || { check FAIL '2. PDF has no .tsr attachment; save it manually and use --tsr' core; finish; }
    check PASS '2. PDF .tsr attachment extracted locally'
fi
hash_file 'RFC 3161 token' "$tsr"
[ -z "$original" ] || hash_file 'Original file' "$original"
original_hash=${HASH-}
[ -z "$archived_ocsp" ] || hash_file 'Archived OCSP response' "$archived_ocsp"

if ! ssl "$tmp/token-text" ts -reply -in "$tsr" -text; then
    check FAIL '2. Token cannot be parsed as an RFC 3161 response' core; finish
fi
serial=$(field 'Serial number' "$tmp/token-text")
token_time=$(field 'Time stamp' "$tmp/token-text")
algorithm=$(field 'Hash Algorithm' "$tmp/token-text")
policy=$(field 'Policy OID' "$tmp/token-text")
tsa=$(field 'TSA' "$tmp/token-text")
accuracy=$(field 'Accuracy' "$tmp/token-text")
imprint=$(awk '
    /^Message data:/ {capture=1; next}
    capture && /^[[:space:]]+[[:xdigit:]]+[[:space:]]*-/ {
        line=$0; sub(/^[[:space:]]+[[:xdigit:]]+[[:space:]]*-[[:space:]]*/, "", line)
        sub(/  .*/, "", line); gsub(/[-[:space:]]/, "", line); printf "%s", line; next
    }
    capture {exit}
' "$tmp/token-text" | tr '[:upper:]' '[:lower:]')
if [ "$(field Status "$tmp/token-text")" = 'Granted.' ]; then check PASS '2. Token status: Granted'
else check FAIL '2. Token status is not Granted' core; fi
if [ "$policy" = 0.4.0.2023.1.1 ]; then check PASS "2. Policy OID: $policy"
else check WARN "2. Unexpected policy OID: $policy"; fi
if [ "$algorithm" = sha256 ] && printf '%s\n' "$imprint" | grep -Eq '^[[:xdigit:]]{64}$'; then
    check PASS "2. SHA-256 message imprint: $imprint"
else check FAIL "2. Expected SHA-256 imprint; found $algorithm / $imprint" core; finish; fi
case "$tsa" in
    *'B-Trust Qualified Time Stamp Authority'*) check PASS "2. TSA: $tsa" ;;
    *) check FAIL '2. Not a BORICA token — this guide does not apply' core; finish ;;
esac
if ! token_epoch=$(epoch "$token_time"); then check FAIL '2. Cannot convert token UTC time to epoch' core; finish; fi
printf '%s\n' "$serial" | grep -Eq '^0[xX][[:xdigit:]]+$' || { check FAIL '2. Invalid token serial' core; serial=unknown; finish; }
if ! sofia_time "$token_epoch"; then
    check FAIL '2. Cannot compute Sofia time (EU rule requires year 1997 or later)' core; finish
fi
case "$offset" in +0300) sofia_label='EEST (UTC+3)' ;; +0200) sofia_label='EET (UTC+2)' ;; *) sofia_label="Europe/Sofia (UTC $offset)" ;; esac
check PASS "2. Serial: $serial; UTC: $token_time; Sofia: $sofia $sofia_label; accuracy: $accuracy"

root=$tmp/root.pem
oper=$tmp/oper.pem
if [ -n "$certs_dir" ]; then
    for name in B-TrustRootQCA.cer btrust-root-qca.pem; do
        if [ -f "$certs_dir/$name" ]; then root=$certs_dir/$name; break; fi
    done
    for name in B-TrustOperationalQCA.cer btrust-oper-qca.pem; do
        if [ -f "$certs_dir/$name" ]; then oper=$certs_dir/$name; break; fi
    done
else
    if ! download "$ROOT_URL" "$root" || ! download "$OPER_URL" "$oper"; then
        check FAIL "3. Cannot download official B-Trust certificates: $(cat "$tmp/curl-error")" core; finish
    fi
fi
if [ ! -r "$root" ] || [ ! -r "$oper" ]; then check FAIL '3. B-Trust root or operational certificate is missing' core; finish; fi
hash_file 'B-Trust root certificate' "$root"
hash_file 'B-Trust operational certificate' "$oper"
check PASS '3. B-Trust certificates obtained'
if ssl "$tmp/root-info" x509 -in "$root" -noout -fingerprint -sha256 &&
    [ "$(normalize_hex "$(sed -n 's/.*Fingerprint=//p' "$tmp/root-info")")" = "$ROOT_PIN" ]; then
    check PASS '3. B-Trust root SHA-256 fingerprint matches pinned root'
else check FAIL '3. B-Trust root fingerprint pin mismatch' core; finish; fi
if ssl "$tmp/oper-chain" verify -CAfile "$root" "$oper"; then
    check PASS '3. Operational certificate chains to pinned root at current time'
elif grep -Eq 'certificate has expired|certificate is not yet valid' "$tmp/oper-chain" &&
    ssl "$tmp/oper-chain-at-time" verify -attime "$token_epoch" -CAfile "$root" "$oper"; then
    check WARN '3. Operational chain outside current validity; chains to pinned root at token time'
else check FAIL '3. Operational certificate does not chain to pinned root' core; fi

if [ -n "$original" ]; then
    if [ "$original_hash" = "$imprint" ]; then check PASS "4. Original file SHA-256 matches token imprint: $original_hash"
    else check FAIL "4. File message imprint mismatch: $original_hash != $imprint" core; fi
fi
if [ -n "$supplied_hash" ]; then
    supplied_hash=$(printf '%s' "$supplied_hash" | tr '[:upper:]' '[:lower:]')
    if [ "$supplied_hash" = "$imprint" ]; then check PASS '4. Supplied SHA-256 matches token imprint'
    else check FAIL "4. Hash message imprint mismatch: $supplied_hash != $imprint" core; fi
fi

# Verify against the parsed imprint, independently of the separate input matches.
# No nonce or saved timestamp request is necessary for -digest verification.
verify_args=(ts -verify -in "$tsr" -digest "$imprint" -CAfile "$root" -untrusted "$oper")
if ssl "$tmp/verify-now" "${verify_args[@]}"; then check PASS '5. Signature and chain verify at current time'
else
    # Require all verification error lines to be validity errors. Never mask an
    # invalid signature, imprint, purpose or chain behind an expiry message.
    errors=$(sed -n '/Verify error:/p; /error [0-9][0-9]* at /p; /:error:/p' "$tmp/verify-now")
    other_errors=$(printf '%s\n' "$errors" | grep -Ev 'certificate has expired|certificate is not yet valid|:ts_verify_cert:certificate verify error:|^[[:space:]]*$' || true)
    if grep -Eq 'certificate has expired|certificate is not yet valid' "$tmp/verify-now" && [ -z "$other_errors" ]; then
        check WARN '5. Current-time chain is outside certificate validity; token-time check follows'
    else check FAIL '5. Signature/chain verification at current time failed for a non-validity reason' core; fi
fi
if ssl "$tmp/verify-at-time" "${verify_args[@]}" -attime "$token_epoch"; then
    check PASS "5. CORE: signature and chain verify at token time (epoch $token_epoch)"
else check FAIL '5. CORE: signature/chain verification at token time failed' core; fi

tsa_cert=$tmp/tsa.pem
if ! ssl "$tmp/extract-token" ts -reply -in "$tsr" -token_out -out "$tmp/token.p7s" ||
    ! ssl "$tmp/extract-certs" pkcs7 -inform DER -in "$tmp/token.p7s" -print_certs -out "$tsa_cert"; then
    check FAIL '6. Cannot extract TSA certificate' core; finish
fi
# B-Trust tokens contain the signer only. Reject ambiguity instead of assuming
# that the first of multiple embedded certificates is the actual signer.
if [ "$(grep -c '^-----BEGIN CERTIFICATE-----' "$tsa_cert")" -ne 1 ]; then
    check FAIL '6. Expected exactly one embedded TSA signer certificate; manual review required' core; finish
fi
if ! ssl "$tmp/tsa-info" x509 -in "$tsa_cert" -noout -subject -issuer -serial -dates -fingerprint -sha256 -text; then
    check FAIL '6. Cannot parse embedded TSA certificate' core; finish
fi
cert_serial=$(sed -n 's/^serial=//p' "$tmp/tsa-info")
cert_fingerprint=$(sed -n 's/.*Fingerprint=//p' "$tmp/tsa-info")
not_before=$(sed -n 's/^notBefore=//p' "$tmp/tsa-info")
not_after=$(sed -n 's/^notAfter=//p' "$tmp/tsa-info")
check PASS "6. TSA $(sed -n '/^subject=/p' "$tmp/tsa-info"); $(sed -n '/^issuer=/p' "$tmp/tsa-info")"
check PASS "6. TSA serial: $cert_serial; validity: $not_before — $not_after; SHA-256: $cert_fingerprint"
eku=$(awk '/X509v3 Extended Key Usage:/ {print; getline; print}' "$tmp/tsa-info")
if printf '%s\n' "$eku" | grep -q critical && printf '%s\n' "$eku" | grep -q 'Time Stamping'; then
    check PASS '6. TSA EKU: Time Stamping, critical'
else check FAIL '6. TSA lacks critical Time Stamping EKU (core signer requirement)' core; fi
before_epoch=$(epoch "$not_before")
after_epoch=$(epoch "$not_after")
if [ -n "$before_epoch" ] && [ -n "$after_epoch" ] && [ "$token_epoch" -ge "$before_epoch" ] && [ "$token_epoch" -le "$after_epoch" ]; then
    check PASS '6. Token time lies within TSA certificate validity'
else check FAIL '6. Token time outside TSA certificate validity (core chain requirement)' core; fi

# Verified revocation evidence can contradict the otherwise valid signature.
revoked() {
    local source=$1 when=$2 reason=$3 revoked_epoch
    if revoked_epoch=$(epoch "$when"); then
        if [ "$revoked_epoch" -le "$token_epoch" ]; then
            check FAIL "$source: TSA revoked at/before token time: $when; reason: $reason (core chain invalidated)" core
        else
            check WARN "$source: TSA revoked after token time: $when; reason: $reason; revocation after issuance does not by itself invalidate the timestamp"
        fi
    else check WARN "$source: TSA revoked; cannot interpret revocation time: $when; reason: $reason"; fi
    case "$reason" in *[Kk]ey*[Cc]ompromise*) check WARN "$source: keyCompromise — ask BORICA about the effective compromise time" ;; esac
}

inspect_ocsp() {
    local source=$1 response=$2 archived=$3 produced produced_epoch delta status when reason
    local ocsp_args
    ocsp_args=(ocsp -respin "$response" -issuer "$oper" -cert "$tsa_cert" -CAfile "$root" -no_nonce -resp_text)
    if [ "$archived" -eq 1 ]; then
        # First read the claimed production time, then authenticate the response
        # and its signer chain at that time. Never trust this preliminary parse.
        if ! ssl "$tmp/ocsp-parse" ocsp -respin "$response" -noverify -resp_text; then
            check WARN "$source: cannot parse archived DER OCSP response"; return
        fi
        produced=$(sed -n 's/^[[:space:]]*Produced At: *//p' "$tmp/ocsp-parse" | head -n 1)
        if ! produced_epoch=$(epoch "$produced"); then
            check WARN "$source: unparseable archived Produced At: $produced"; return
        fi
        ocsp_args+=( -attime "$produced_epoch" )
    fi
    if ! ssl "$tmp/ocsp-check" "${ocsp_args[@]}"; then
        check WARN "$source: OCSP signature, freshness or certificate lookup failed; see appendix"; return
    fi
    if ! grep -q 'Response verify OK' "$tmp/ocsp-check"; then
        check WARN "$source: no authenticated OCSP response"; return
    fi
    # Exactly one -cert checks issuer name/key hashes AND serial. Its summary
    # is unindented; ignore indented Cert Status entries in -resp_text. Native
    # Windows OpenSSL prints a converted filename, not our MSYS /tmp path.
    status=$(awk '/^[^[:space:]].*: (good|revoked|unknown)$/ {sub(/^.*: /, ""); print; exit}' "$tmp/ocsp-check")
    if grep -Eq 'Status times invalid|status expired|status not yet valid' "$tmp/ocsp-check"; then
        check WARN "$source: OCSP status is stale or not yet current; authenticated status applies only to the response interval"
    fi
    if [ "$status" = good ]; then check PASS "$source: verified OCSP signature; TSA serial $cert_serial matches; status good"
    elif [ "$status" = revoked ]; then
        when=$(sed -n 's/^[[:space:]]*Revocation Time: *//p' "$tmp/ocsp-check" | tail -n 1)
        reason=$(sed -n 's/^[[:space:]]*Reason: *//p; s/^[[:space:]]*Revocation Reason: *//p' "$tmp/ocsp-check" | tail -n 1)
        revoked "$source" "$when" "${reason:-unspecified}"
    else check WARN "$source: authenticated OCSP status ${status:-unknown/no matching TSA serial}"; fi
    produced=$(sed -n 's/^[[:space:]]*Produced At: *//p' "$tmp/ocsp-check" | head -n 1)
    if produced_epoch=$(epoch "$produced"); then
        delta=$((produced_epoch - token_epoch))
        check PASS "$source: Produced At: $produced; offset from token: $delta seconds"
        [ "$archived" -eq 0 ] || check WARN "$source: archived response describes its production time, not necessarily status at token issuance"
    else check WARN "$source: cannot interpret OCSP Produced At: $produced"; fi
}

if [ "$offline" -eq 1 ]; then
    check SKIP '7. Online OCSP and CRL (--offline; no network)'
else
    cert_ocsp=$(sed -n 's/^[[:space:]]*OCSP - URI://p' "$tmp/tsa-info" | head -n 1)
    cert_crl=$(awk '/X509v3 CRL Distribution Points:/ {capture=1; next} capture && /URI:/ {sub(/.*URI:/, ""); print; exit} capture && /X509v3/ {exit}' "$tmp/tsa-info")
    if [ "$cert_ocsp" = "$OCSP_URL" ]; then
        if ssl "$tmp/ocsp-live" ocsp -issuer "$oper" -cert "$tsa_cert" -url "$cert_ocsp" -CAfile "$root" -no_nonce -timeout 20 -resp_text -respout "$tmp/ocsp.der"; then
            hash_file 'Downloaded OCSP response' "$tmp/ocsp.der"
            inspect_ocsp '7. Online OCSP' "$tmp/ocsp.der" 0
        else
            [ ! -s "$tmp/ocsp.der" ] || hash_file 'Downloaded OCSP response' "$tmp/ocsp.der"
            check WARN '7. Online OCSP unavailable or response verification failed; see appendix'
        fi
    else check WARN "7. OCSP URL absent or outside allowed official source: $cert_ocsp"; fi
    if [ "$cert_crl" = "$CRL_URL" ] && download "$cert_crl" "$tmp/crl.der"; then
        hash_file 'Downloaded CRL' "$tmp/crl.der"
        if ssl "$tmp/crl-verify" crl -inform DER -in "$tmp/crl.der" -noout -verify -CAfile "$oper" &&
            grep -q '^verify OK' "$tmp/crl-verify" &&
            ssl "$tmp/crl-text" crl -inform DER -in "$tmp/crl.der" -noout -text; then
            crl_record=$(awk -v wanted="$(normalize_hex "$cert_serial")" '
                /Serial Number:/ {s=$0; sub(/.*Serial Number: */, "", s); gsub(/:/, "", s); sub(/^0+/, "", s); match_serial=(toupper(s)==wanted)}
                match_serial && /Revocation Date:/ {sub(/.*Revocation Date: */, ""); when=$0}
                match_serial && /X509v3 CRL Reason Code:/ {getline; gsub(/^[[:space:]]+|[[:space:]]+$/, ""); reason=$0}
                END {if (when!="") printf "%s|%s", when, reason}
            ' "$tmp/crl-text")
            if [ -n "$crl_record" ]; then revoked '7. CRL' "${crl_record%%|*}" "${crl_record#*|}"
            else check PASS "7. CRL signature verified against operational cert; TSA serial $cert_serial not listed"; fi
            crl_last=$(sed -n 's/^[[:space:]]*Last Update: *//p' "$tmp/crl-text" | head -n 1)
            crl_next=$(sed -n 's/^[[:space:]]*Next Update: *//p' "$tmp/crl-text" | head -n 1)
            check PASS "7. CRL Last Update: $crl_last; Next Update: $crl_next"
            now_epoch=$(date -u +%s)
            if next_epoch=$(epoch "$crl_next") && last_epoch=$(epoch "$crl_last") && [ "$next_epoch" -ge "$now_epoch" ] && [ "$last_epoch" -le "$now_epoch" ]; then :
            else check WARN '7. CRL is stale, not yet current or has unparseable update times'; fi
        else check WARN '7. CRL signature verification or DER parsing failed'; fi
    else check WARN '7. CRL URL absent/outside allowed source, or download failed'; fi
fi
if [ -n "$archived_ocsp" ]; then inspect_ocsp '8. Archived OCSP' "$archived_ocsp" 1
else check SKIP '8. No --ocsp-file supplied'; fi

if [ "$offline" -eq 1 ]; then check SKIP '9. Bulgarian national trusted list (--offline)'
elif download "$TL_URL" "$tmp/tl.xml"; then
    hash_file 'Bulgarian national trusted list' "$tmp/tl.xml"
    # Streaming XML subset: local names only; scope to current ServiceInformation,
    # never combine a history certificate with a current service's status.
    awk -v directory="$tmp" '
        BEGIN {RS="<"; service=0; info=0; collecting=""; count=0}
        {
            end=index($0, ">"); if (!end) next
            tag=substr($0,1,end-1); value=substr($0,end+1)
            closing=(substr(tag,1,1)=="/"); sub(/^\//,"",tag); sub(/[[:space:]\/].*/,"",tag); sub(/^.*:/,"",tag)
            if (tag=="TSPService" && !closing) {service=1; type=""; status=""; start=""; certs=""}
            if (service && tag=="ServiceInformation") info=!closing
            if (service && info) {
                if (!closing && (tag=="ServiceTypeIdentifier" || tag=="ServiceStatus" || tag=="StatusStartingTime" || tag=="X509Certificate")) collecting=tag
                if (closing && tag==collecting) collecting=""
                if (collecting=="ServiceTypeIdentifier") type=type value
                if (collecting=="ServiceStatus") status=status value
                if (collecting=="StatusStartingTime") start=start value
                if (collecting=="X509Certificate") {
                    gsub(/[[:space:]]/,"",value)
                    if (value!="") {count++; file=directory "/tl-cert-" count ".b64"; print value > file; close(file); certs=certs count " "}
                }
            }
            if (tag=="TSPService" && closing) {
                gsub(/[[:space:]]/,"",type); gsub(/[[:space:]]/,"",status); gsub(/[[:space:]]/,"",start)
                if (type ~ /\/Svctype\/TSA\/QTST$/) {n=split(certs,files," "); for(i=1;i<=n;i++) if(files[i]!="") print directory "/tl-cert-" files[i] ".b64|" status "|" start}
                service=0; info=0; collecting=""
            }
        }
    ' "$tmp/tl.xml" > "$tmp/tl-services"
    found=0
    granted=0
    while IFS='|' read -r b64 status starting; do
        [ -n "$b64" ] || continue
        if ssl "$tmp/decode-output" base64 -d -A -in "$b64" -out "$tmp/tl-cert.der" &&
            ssl "$tmp/tl-cert-info" x509 -inform DER -in "$tmp/tl-cert.der" -noout -fingerprint -sha256; then
            fingerprint=$(sed -n 's/.*Fingerprint=//p' "$tmp/tl-cert-info")
            if [ "$(normalize_hex "$fingerprint")" = "$(normalize_hex "$cert_fingerprint")" ]; then
                found=1
                case "$status" in
                    */granted)
                        if start_epoch=$(epoch "$starting") && [ "$start_epoch" -le "$token_epoch" ]; then
                            granted=1; check PASS "9. TSA fingerprint listed in Bulgarian QTST service; status granted since $starting"
                        fi ;;
                esac
                check PASS "9. Matching QTST service status: $status; StatusStartingTime: $starting"
            fi
        fi
    done < "$tmp/tl-services"
    if [ "$found" -eq 0 ]; then check WARN '9. TSA fingerprint not found in current QTST service entries; manual check of service history required'
    elif [ "$granted" -eq 0 ]; then check WARN '9. Service status/time does not establish grant at issuance; manual check of service history required'; fi
    check WARN '9. Trusted-list XML fetched over HTTPS; XML signature/EU LOTL chain and service history require independent validation'
else check WARN '9. Bulgarian trusted list download failed; manual check required'; fi

if [ -n "$supplied_serial" ]; then
    if [ "$(normalize_hex "$supplied_serial")" = "$(normalize_hex "$serial")" ]; then check PASS "10. Certificate serial matches token: $serial"
    else check FAIL "10. Certificate serial mismatch: $supplied_serial != $serial" core; fi
fi
if [ -n "$supplied_time" ]; then
    if [ "$supplied_time" = "$sofia" ]; then check PASS "10. Certificate Sofia wall-clock time matches: $sofia $sofia_label"
    else check FAIL "10. Certificate Sofia wall-clock time mismatch: $supplied_time != $sofia $sofia_label" core; fi
fi
if [ -z "$supplied_serial$supplied_time" ]; then check SKIP '10. No certificate serial/time comparisons requested'; fi
finish
