#!/bin/bash
# PQCrypta Discovery Agent — verifying installer
# Usage: curl -sSL https://api.pqcrypta.com/stream/downloads/discovery-agent/install.sh | bash
#
# This script fails CLOSED: it downloads the binary, verifies its SHA-256 against
# the signed SHA256SUMS, verifies the Ed25519 signature of SHA256SUMS against the
# public key PINNED BELOW, and only then marks the binary executable. If any check
# fails — or the tools to check are missing — it aborts without installing.
set -euo pipefail

API_BASE="${PQCRYPTA_API_URL:-https://api.pqcrypta.com}"
BASE="${API_BASE}/stream/downloads/discovery-agent"
BINARY_NAME="pqcrypta-discovery"

# --- Pinned signing key (Ed25519). Verification uses THIS, not a downloaded key. ---
read -r -d '' PQCRYPTA_PUBKEY <<'PUBKEY_EOF' || true
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA59xCUOYhA0b7p1ZEMdV0HjQbHwKgvsPNRmots+TgaUQ=
-----END PUBLIC KEY-----
PUBKEY_EOF

os="$(uname -s)"; arch="$(uname -m)"
case "$os" in
    Linux)
        [ "$arch" != "x86_64" ] && echo "Warning: only an x86_64 Linux build is published; this host is $arch." >&2
        url="${BASE}/linux"; sums_name="pqcrypta-discovery" ;;
    Darwin)
        if [ "$arch" = "arm64" ]; then url="${BASE}/macos"; sums_name="pqcrypta-discovery-macos"
        else url="${BASE}/macos-intel"; sums_name="pqcrypta-discovery-macos-intel"; fi ;;
    *) echo "Unsupported OS: $os. Prebuilt binaries: Linux x86_64, macOS (Apple Silicon + Intel)." >&2; exit 1 ;;
esac

tmp="$(mktemp -d)"; trap 'rm -rf "$tmp"' EXIT

echo "Downloading ${BINARY_NAME} and release-integrity files ..."
curl -fsSL -o "$tmp/$BINARY_NAME" "$url"
curl -fsSL -o "$tmp/SHA256SUMS" "${BASE}/verify/SHA256SUMS"
curl -fsSL -o "$tmp/SHA256SUMS.sig" "${BASE}/verify/SHA256SUMS.sig"
printf '%s\n' "$PQCRYPTA_PUBKEY" > "$tmp/signing.pub"

# 1) Verify the Ed25519 signature of SHA256SUMS against the PINNED public key.
if command -v openssl >/dev/null 2>&1; then
    if openssl pkeyutl -verify -pubin -inkey "$tmp/signing.pub" -rawin         -in "$tmp/SHA256SUMS" -sigfile "$tmp/SHA256SUMS.sig" >/dev/null 2>&1; then
        echo "  ✓ Ed25519 signature valid (SHA256SUMS signed by the pinned PQCrypta key)"
        echo "    (a post-quantum ML-DSA-65 / FIPS 204 signature is also published at"
        echo "     ${BASE}/verify/SHA256SUMS.mldsa.sig for quantum-resistant verification)"
    else
        echo "  ✗ SIGNATURE VERIFICATION FAILED — aborting, nothing installed." >&2; exit 1
    fi
else
    echo "  ✗ openssl not found — cannot verify the signature. Aborting." >&2
    echo "    Install openssl, or download + verify manually. Nothing installed." >&2; exit 1
fi

# 2) Verify the binary's SHA-256 matches the (now-trusted) SHA256SUMS entry.
expected="$(awk -v f="$sums_name" '$2==f {print $1}' "$tmp/SHA256SUMS")"
[ -z "$expected" ] && { echo "  ✗ no checksum for $sums_name in SHA256SUMS. Aborting." >&2; exit 1; }
if command -v sha256sum >/dev/null 2>&1; then actual="$(sha256sum "$tmp/$BINARY_NAME" | awk '{print $1}')"
elif command -v shasum >/dev/null 2>&1; then actual="$(shasum -a 256 "$tmp/$BINARY_NAME" | awk '{print $1}')"
else echo "  ✗ no sha256sum/shasum available. Aborting." >&2; exit 1; fi
if [ "$actual" = "$expected" ]; then
    echo "  ✓ checksum valid ($actual)"
else
    echo "  ✗ CHECKSUM MISMATCH — expected $expected, got $actual. Aborting." >&2; exit 1
fi

# All checks passed — install.
mv "$tmp/$BINARY_NAME" "./$BINARY_NAME"
chmod +x "./$BINARY_NAME"
echo ""
echo "Installed and verified ./${BINARY_NAME}"
echo ""
echo "Next steps:"
echo "  Submit:   ./${BINARY_NAME} --config agent-config.toml --api-url ${API_BASE} --api-key YOUR_KEY"
echo "  Offline:  ./${BINARY_NAME} --config agent-config.toml --offline-report ./assessment"
