#!/usr/bin/env bash
# GhostWire release verification — run inside a release directory containing
# SHA256SUMS, SHA256SUMS.sig.json and release-signing-key.pub.json.
# Needs only: openssl, xxd, grep, sed (all standard on macOS/Linux).
#
# Usage: ./verify.sh [downloaded-artifact-filename]
set -euo pipefail

for f in SHA256SUMS SHA256SUMS.sig.json release-signing-key.pub.json; do
  [ -f "$f" ] || { echo "missing $f — download it alongside this script first" >&2; exit 1; }
done

PUBHEX=$(grep -o '"public_key_hex"[^,}]*' release-signing-key.pub.json | sed -E 's/.*"([0-9a-f]+)"/\1/')
SIGHEX=$(grep -o '"signature_hex"[^,}]*'   SHA256SUMS.sig.json         | sed -E 's/.*"([0-9a-f]+)"/\1/')

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
echo -n "302a300506032b6570032100${PUBHEX}" | xxd -r -p > "$TMP/pub.der"
xxd -r -p <<< "$SIGHEX" > "$TMP/sig.bin"
openssl pkey -pubin -inform DER -in "$TMP/pub.der" -outform PEM -out "$TMP/pub.pem" 2>/dev/null

echo "== checking SHA256SUMS is signed by the published release key =="
if openssl pkeyutl -verify -pubin -inkey "$TMP/pub.pem" -rawin -in SHA256SUMS -sigfile "$TMP/sig.bin" >/dev/null 2>&1; then
  echo "OK — SHA256SUMS signature verified against release-signing-key.pub.json"
else
  echo "FAILED — signature does NOT match. Do not trust this release directory." >&2
  exit 1
fi

if [ "${1:-}" != "" ]; then
  echo
  echo "== checking $1 against SHA256SUMS =="
  ACTUAL=$(shasum -a 256 "$1" | awk '{print $1}')
  EXPECTED=$(grep -F "  $1" SHA256SUMS | awk '{print $1}' || true)
  if [ -z "$EXPECTED" ]; then
    echo "FAILED — $1 is not listed in SHA256SUMS" >&2
    exit 1
  fi
  if [ "$ACTUAL" = "$EXPECTED" ]; then
    echo "OK — $1 matches its recorded SHA-256"
  else
    echo "FAILED — hash mismatch. expected $EXPECTED got $ACTUAL" >&2
    exit 1
  fi
fi

echo
echo "All checks passed."
