#!/usr/bin/env bash
# ProofSnap evidence verifier (POSIX / macOS / Linux)
# Run from the package root:   bash verification/verify.sh
# or from this folder:         cd verification && bash verify.sh
# Requires: python3, openssl. (ots + a TSA root cert only for the optional deep
# timestamp checks printed at the end.)
set -euo pipefail
# Resolve the package root = the parent of this script's directory.
cd "$(dirname "$0")/.."

fail=0
echo "============================================================"
echo " ProofSnap Evidence Verification"
echo "============================================================"

echo
echo "[1/5] File integrity — SHA-256 of every file vs manifest.json"
echo "------------------------------------------------------------"
python3 - "$PWD" <<'PY' || fail=1
import json, hashlib, os, sys
root = sys.argv[1]
manifest = json.load(open(os.path.join(root, "manifest.json")))
ok = True
for name, expected in manifest.items():
    if name in ("evidence_id", "manifest.json"):
        continue
    path = os.path.join(root, name)
    if not os.path.isfile(path):
        print(f"  MISSING  {name}"); ok = False; continue
    with open(path, "rb") as fh:
        actual = hashlib.sha256(fh.read()).hexdigest()
    print(("  OK       " if actual == expected else "  MISMATCH ") + name)
    if actual != expected:
        ok = False
print()
print("  RESULT:", "all files match" if ok else "ONE OR MORE FILES FAILED")
sys.exit(0 if ok else 1)
PY

echo
echo "[2/5] Manifest signature — RSA over manifest.json"
echo "------------------------------------------------------------"
if openssl dgst -sha256 -verify publickey.pem -signature manifest.sig manifest.json; then
  echo "  Signature OK — manifest.json is authentic and untampered"
else
  echo "  Signature FAILED"; fail=1
fi

echo
echo "[3/5] Forensic hash chain — recompute over forensic_log.json"
echo "------------------------------------------------------------"
if [ -f forensic_log.json ]; then
python3 - "$PWD" <<'PY' || fail=1
import json, hashlib, os, sys
root = sys.argv[1]
def sha(s):
    return hashlib.sha256(s.encode("utf-8")).hexdigest()
log = json.load(open(os.path.join(root, "forensic_log.json")))
try:
    coc = json.load(open(os.path.join(root, "chain_of_custody.json")))
except Exception:
    coc = {}
hc = log.get("hash_chain", {}) or {}
genesis = hc.get("genesis_hash")
ops = log.get("operations", []) or []
ORDER = ["operation_id","operation_type","sequence_number","timestamp_local","timestamp_ntp","ntp_offset_ms","duration_ms","result","hash_before","hash_after","details","error_message"]
def entry_hash(op):
    obj = {}
    for k in ORDER:
        if k in op:
            obj[k] = op[k]
    return sha(json.dumps(obj, separators=(",", ":"), ensure_ascii=False))
ok = True
prev = genesis
cumulative = genesis
for i, op in enumerate(ops):
    seq = op.get("sequence_number")
    if op.get("previous_entry_hash") != prev:
        print("  CHAIN BREAK at op #%d (seq %s): previous_entry_hash mismatch" % (i + 1, seq)); ok = False
    eh = entry_hash(op)
    cumulative = sha(cumulative + eh)
    if op.get("cumulative_hash") != cumulative:
        print("  CHAIN BREAK at op #%d (seq %s): cumulative_hash mismatch" % (i + 1, seq)); ok = False
    prev = eh
print("")
if cumulative == hc.get("final_hash"):
    print("  Final hash matches forensic_log.hash_chain.final_hash")
else:
    print("  Final hash does NOT match forensic_log.hash_chain.final_hash"); ok = False
coc_final = coc.get("forensic_log_final_chain_hash")
if coc_final is None and isinstance(coc.get("integrity"), dict):
    coc_final = coc["integrity"].get("forensic_log_final_chain_hash")
if coc_final is not None:
    if cumulative == coc_final:
        print("  Final hash matches chain_of_custody.forensic_log_final_chain_hash")
    else:
        print("  Final hash does NOT match chain_of_custody reference"); ok = False
print("")
print("  RESULT: " + ("hash chain intact (%d operations)" % len(ops) if ok else "HASH CHAIN FAILED"))
sys.exit(0 if ok else 1)
PY
else
  echo "  forensic_log.json not present — skipped."
fi

echo
echo "[4/5] eIDAS RFC 3161 qualified timestamp"
echo "------------------------------------------------------------"
if [ -f manifest.json.tsr ]; then
  echo "  manifest.json.tsr present. Deep verify (needs the TSA root cert):"
  echo "    openssl ts -verify -in manifest.json.tsr -data manifest.json -CAfile <tsa-root>.pem"
  echo "  Certificate chain + OCSP/CRL are in eidas_validation.json (see its"
  echo "  'summary' block at the top for a quick pass/fail read)."
else
  echo "  Not present (package was not eIDAS-stamped)."
fi

echo
echo "[5/5] Bitcoin OpenTimestamps anchor"
echo "------------------------------------------------------------"
if [ -f manifest.json.ots ]; then
  echo "  manifest.json.ots present. Deep verify (needs the ots client):"
  echo "    ots verify manifest.json.ots -f manifest.json"
else
  echo "  Not present (package was not OTS-stamped)."
fi

echo
echo "============================================================"
if [ "$fail" -eq 0 ]; then
  echo " RESULT: PASS — integrity and signature verified."
else
  echo " RESULT: FAIL — see the failed step(s) above."
fi
echo "============================================================"
exit "$fail"
