"""Signs and verifies the SHA256SUMS of NEXXVU images (R11, Hani #1 2026-10-26).

The image lists are signed with the release key, the same key that signs every release and channel index, loaded by
the release tooling (test_trust.load) - the key never leaves it and nothing prints it. The signed message is
domain-separated, so an image-list signature can never stand for a release or channel signature, nor the reverse:

    message = b"NEXXVU image SHA256SUMS v1\\n" + <the SHA256SUMS file>
    <name>.SHA256SUMS.sig = base64(Ed25519 signature of message) + "\\n"

    sign_sums.py sign --trust-dir DIR FILE.SHA256SUMS [...]        writes FILE.SHA256SUMS.sig next to each
    sign_sums.py verify --public-key KEY FILE.SHA256SUMS            KEY: the update centers' update-signing-public-key
                                                                     (base64 of the 32-byte Ed25519 key)

verify needs only Python 3 and the `cryptography` package; it prints SIGNATURE-OK or exits non-zero.
"""
import argparse
import base64
import sys
from pathlib import Path

PREFIX = b"NEXXVU image SHA256SUMS v1\n"


def message(sums: bytes) -> bytes:
    if not sums or len(sums) > 65536 or not sums.endswith(b"\n"):
        raise SystemExit("not a SHA256SUMS file")
    return PREFIX + sums


def sign(trust_dir: Path, files: list[Path]) -> None:
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "activation" / "rehearsal"))
    import test_trust
    key = test_trust.load(trust_dir)["release"]
    public = key.public_key()
    for path in files:
        raw = message(path.read_bytes())
        signature = key.sign(raw)
        public.verify(signature, raw)
        path.with_name(path.name + ".sig").write_bytes(base64.b64encode(signature) + b"\n")
        print(f"SIGNED {path.name}")


def verify(public_key: Path, path: Path) -> None:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    raw_key = base64.b64decode(public_key.read_bytes().strip(), validate=True)
    if len(raw_key) != 32:
        raise SystemExit("the public key must be 32 bytes (base64)")
    signature = base64.b64decode(path.with_name(path.name + ".sig").read_bytes().strip(), validate=True)
    Ed25519PublicKey.from_public_bytes(raw_key).verify(signature, message(path.read_bytes()))   # raises if invalid
    print(f"SIGNATURE-OK {path.name}")


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = parser.add_subparsers(dest="command", required=True)
    s = sub.add_parser("sign"); s.add_argument("--trust-dir", type=Path, required=True); s.add_argument("files", type=Path, nargs="+")
    v = sub.add_parser("verify"); v.add_argument("--public-key", type=Path, required=True); v.add_argument("file", type=Path)
    args = parser.parse_args(argv)
    if args.command == "sign":
        sign(args.trust_dir, args.files)
    else:
        verify(args.public_key, args.file)
    return 0


if __name__ == "__main__":
    sys.exit(main())
