#!/usr/bin/env bash
# quantumunix-verify.sh
# Standalone verifier for any QuantumUnix release artifact you already have on disk.
# Checks SHA-256 (strict) and cosign signature (if available).
#
# Usage:
#   ./quantumunix-verify.sh <FILE>
#
# Expects these neighbours next to <FILE>:
#   <FILE>.sha256   (required)
#   <FILE>.sig      (optional, cosign blob signature)
#   <FILE>.pem      (optional, cosign certificate)
#
# Author: Dr. Sarunas Grigaliunas
# License: MIT

set -Eeuo pipefail

log() { printf '[qu] %s\n' "$*" >&2; }
die() { printf '[qu:error] %s\n' "$*" >&2; exit 1; }

[[ $# -eq 1 ]] || { echo "usage: $0 <file>"; exit 2; }

FILE="$1"
[[ -f "${FILE}" ]] || die "no such file: ${FILE}"

DIR="$(cd "$(dirname "${FILE}")" && pwd)"
BASENAME="$(basename "${FILE}")"
cd "${DIR}"

[[ -f "${BASENAME}.sha256" ]] || die "missing checksum file: ${BASENAME}.sha256"

log "verifying SHA-256 of ${BASENAME}..."
sha256sum -c "${BASENAME}.sha256" || die "SHA-256 mismatch"

if command -v cosign >/dev/null && [[ -f "${BASENAME}.sig" && -f "${BASENAME}.pem" ]]; then
  log "verifying cosign signature..."
  cosign verify-blob \
    --certificate "${BASENAME}.pem" \
    --signature   "${BASENAME}.sig" \
    --certificate-identity-regexp '.*' \
    --certificate-oidc-issuer-regexp '.*' \
    "${BASENAME}" \
    || die "cosign verification failed"
  log "cosign signature OK."
else
  log "cosign step skipped (binary or .sig/.pem absent). SHA-256 verified only."
fi

log "OK: ${BASENAME}"
