#!/usr/bin/env bash
# verify_audit.sh — Relay 22 Step 6 / Relay 52 iter5
# Recomputes the Merkle root from the PUBLIC_AUDIT_FINAL artifacts directory
# and compares against merkle_root.txt.
# A customer can run this to verify the bundle hasn't been tampered with.
#
# Usage: verify_audit.sh [path/to/bundle_dir]
#   Default bundle dir: tests/audit/PUBLIC_AUDIT_FINAL
#
# Merkle algorithm:
#   1. SHA-256 every file in artifacts/
#   2. Deduplicate hashes (multiple source files can map to one artifact)
#   3. Sort unique hashes lexically
#   4. Concatenate sorted hashes
#   5. SHA-256 the concatenation
set -euo pipefail

WORKDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PUBLIC_AUDIT="${1:-$WORKDIR/tests/audit/PUBLIC_AUDIT_FINAL}"
MERKLE="$PUBLIC_AUDIT/merkle_root.txt"
ARTIFACTS="$PUBLIC_AUDIT/artifacts"

if [ ! -f "$MERKLE" ]; then
  echo "ERROR: $MERKLE not found"
  exit 1
fi

if [ ! -d "$ARTIFACTS" ]; then
  echo "ERROR: $ARTIFACTS not found"
  exit 1
fi

EXPECTED=$(cat "$MERKLE" | tr -d '[:space:]')

echo "[verify_audit] Recomputing Merkle root from $ARTIFACTS ..."
echo "[verify_audit] Expected: $EXPECTED"

# Collect all file hashes
ALL_HASHES=""
TOTAL=0
while IFS= read -r -d '' file; do
  HASH=$(shasum -a 256 "$file" | awk '{print $1}')
  ALL_HASHES="${ALL_HASHES}${HASH}"
  TOTAL=$((TOTAL + 1))
done < <(find "$ARTIFACTS" -type f -print0 | sort -z)

echo "[verify_audit] Hashed $TOTAL artifact files"

# Merkle root: deduplicate, sort unique hashes, concatenate, SHA-256
# sort -u deduplicates so that identical source files that share an artifact
# path are counted once, matching the build script's set(all_hashes).
SORTED_CONCAT=$(echo "$ALL_HASHES" | fold -w 64 | sort -u | tr -d '\n')
COMPUTED=$(echo -n "$SORTED_CONCAT" | shasum -a 256 | awk '{print $1}')

echo "[verify_audit] Computed:  $COMPUTED"

if [ "$COMPUTED" = "$EXPECTED" ]; then
  echo ""
  echo "VERIFY PASS — Merkle root matches. Bundle is intact."
  exit 0
else
  echo ""
  echo "VERIFY FAIL — Merkle root mismatch! Bundle may have been modified."
  echo "  Expected: $EXPECTED"
  echo "  Computed: $COMPUTED"
  exit 1
fi
