#!/bin/sh
# verify.sh: walk the whole Interplane receipts list and print its head.
#
#   sh verify.sh            checks https://interplane.io/receipts
#   sh verify.sh ADDRESS    checks a copy served somewhere else
#
# It fetches the list, starts at record 1, and for each record checks three
# things: its number, that it carries the fingerprint (SHA-256) of the record
# before it, and that its evidence file has the fingerprint the record names.
# It stops at the first record that fails, and it fails when the list does
# not end with a line feed, so a cut-off last record is not skipped. It
# needs curl, cut, tail and either sha256sum or shasum. It writes only to a temporary folder, which it removes.
#
# A head that matches the page shows the list and the page agree. To know the
# list was not replaced after publication, compare the head with one you saved
# earlier, or with content/receipts/head.txt in the site's source.
# Plain Git does not check a signature; a head saved earlier is the stronger comparison.
set -eu
BASE=${1:-https://interplane.io/receipts}
if command -v sha256sum >/dev/null 2>&1; then
  sum() { sha256sum | cut -d' ' -f1; }
else
  sum() { shasum -a 256 | cut -d' ' -f1; }
fi
fail() {
  if [ "$n" -gt 0 ]; then echo "FAIL record $n: $1"; else echo "FAIL: $1"; fi
  exit 1
}
T=$(mktemp -d)
trap 'rm -rf "$T"' 0
n=0
curl -fsS "$BASE/ledger.tsv" -o "$T/ledger.tsv" || fail 'the list could not be fetched'
[ -s "$T/ledger.tsv" ] || fail 'the list is empty'
[ -z "$(tail -c 1 "$T/ledger.tsv")" ] || fail 'the list does not end with a line feed'
prev=GENESIS
while IFS= read -r line; do
  n=$((n + 1))
  seq=$(printf '%s' "$line" | cut -f1)
  payload=$(printf '%s' "$line" | cut -f6)
  link=$(printf '%s' "$line" | cut -f7)
  [ "$seq" = "$n" ] || fail "its number is $seq"
  [ "$link" = "$prev" ] || fail 'it does not carry the fingerprint of the record before it'
  case $payload in *[!0-9a-f]*) fail 'its evidence name is not a fingerprint' ;; esac
  [ "${#payload}" -eq 64 ] || fail 'its evidence name is not a fingerprint'
  curl -fsS "$BASE/payload/$payload.txt" -o "$T/evidence" || fail 'its evidence file could not be fetched'
  [ "$(sum < "$T/evidence")" = "$payload" ] || fail 'its evidence file does not match its fingerprint'
  prev=$(printf '%s' "$line" | sum)
done < "$T/ledger.tsv"
[ "$n" -gt 0 ] || fail 'the list is empty'
echo "records $n"
echo "head $prev"
