#!/bin/sh
# verify.sh: checks this folder against the signed build it claims to be (PREPAIRE-VERA-REFERENCE-GRAPH-DOWNLOAD@1.0.0).
#   ./verify.sh <key fingerprint> [<output_sha256>]
# Give it the fingerprint published apart from this archive (VERA's /reference-graph page, the OpenAPI document,
# GET /api/v1/reference-graph/stats verification.keyFingerprint). The key in allowed_signers comes in this same
# archive, so by itself it proves nothing: anyone could re-sign a changed manifest with a key of their own and put
# that key here. This script is not signed either: read it before running it.
#   0. allowed_signers holds exactly one key, and its fingerprint (ssh-keygen -lf) is the one given.
#   1. The OpenSSH signature on manifest.json, by that key (principal and namespace prepaire-kg-build).
#   2. Every file manifest.json lists (310 CSV files): its size and SHA-256.
#   3. constraints.cypher against manifest.json's constraints_sha256.
#   4. output_sha256 recomputed from the CSV files, as the builder computes it (kg/writer.py content_digest_so_far), and,
#      when given, equal to the published one.
#   5. No CSV file in csv/ that manifest.json does not list.
# Needs ssh-keygen (OpenSSH 8.1 or later) and python3. Reads only; writes nothing. Exit 0 only when every check passes.
set -eu
expected_key=${1:-}
expected_output=${2:-}
if [ -z "$expected_key" ]; then
  echo "usage: ./verify.sh <key fingerprint, SHA256:...> [<output_sha256>]" >&2
  echo "   the fingerprint is published apart from this archive: README.md, section 1" >&2
  exit 1
fi
here=$(cd "$(dirname "$0")" && pwd)
cd "$here"

echo "0. The key in allowed_signers against the fingerprint given"
keys=$(awk '!/^#/ && NF { for (i = 1; i <= NF; i++) if ($i ~ /^(ssh-|ecdsa-|sk-)/) { print $i, $(i + 1); break } }' allowed_signers)
count=$(printf '%s\n' "$keys" | grep -c . || true)
if [ "$count" != 1 ]; then
  echo "   FAIL allowed_signers holds $count keys, not 1"
  exit 1
fi
found=$(printf '%s\n' "$keys" | ssh-keygen -lf - | awk '{ print $2 }')
if [ "$found" != "$expected_key" ]; then
  echo "   FAIL the key in allowed_signers is $found, not $expected_key"
  exit 1
fi
echo "   $found, the fingerprint given"

echo "1. Signature on manifest.json"
ssh-keygen -Y verify -f allowed_signers -I prepaire-kg-build -n prepaire-kg-build -s manifest.json.sig < manifest.json

echo "2-5. Files against manifest.json"
python3 -I - "$here" "$expected_output" <<'PY'
import hashlib, json, os, sys
root, expected_output = sys.argv[1], sys.argv[2]
def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()
m = json.load(open(os.path.join(root, "manifest.json"), encoding="utf-8"))
bad = []
for name, entry in sorted(m["files"].items()):
    path = os.path.join(root, "csv", name)
    if not os.path.isfile(path):
        bad.append(f"{name}: missing")
    elif os.path.getsize(path) != entry["bytes"] or sha256(path) != entry["sha256"]:
        bad.append(f"{name}: differs from manifest.json")
extra = sorted(set(f for f in os.listdir(os.path.join(root, "csv")) if f.endswith(".csv")) - set(m["files"]))
bad += [f"{name}: not listed in manifest.json" for name in extra]
if sha256(os.path.join(root, "constraints.cypher")) != m["constraints_sha256"]:
    bad.append("constraints.cypher: differs from manifest.json")
digest = hashlib.sha256()
for name in sorted(m["files"]):
    if not name.startswith("GraphBuild-"):
        digest.update(f"{name}\x1f{m['files'][name]['sha256']}\x1e".encode("utf-8"))
if digest.hexdigest() != m["output_sha256"]:
    bad.append("output_sha256: does not recompute")
if expected_output and m["output_sha256"] != expected_output:
    bad.append(f"output_sha256: {m['output_sha256']}, not the {expected_output} given")
print(f"   {len(m['files'])} files listed, {len(bad)} problems; build {m['graph_build_id']}, build_hash {m['build_hash']}")
print(f"   {sum(m['nodes'].values())} nodes, {sum(m['edges'].values())} edges, output_sha256 {m['output_sha256']}"
      + (" (the one given)" if expected_output and m["output_sha256"] == expected_output else ""))
for line in bad:
    print("   FAIL " + line)
sys.exit(1 if bad else 0)
PY
echo "All checks passed."
