# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Utilities for assets."""

from pgpy import PGPKeyring
from pgpy.types import Armorable


# mypy complains that PGPKeyring and Armorable are untyped, which is true,
# but we can't fix that here.
class ExportablePGPKeyring(PGPKeyring, Armorable):  # type: ignore[misc]
    """
    An OpenPGP keyring that can be exported as a single public key block.

    Only public keys can be exported this way.
    """

    @property
    def magic(self) -> str:
        """The magic string identifier for this PGP type."""
        return "PUBLIC KEY BLOCK"

    def __bytearray__(self) -> bytearray:
        """Return the public key block as a byte array."""
        _bytes = bytearray()
        for fingerprint in self.fingerprints(
            keyhalf="public", keytype="primary"
        ):
            with self.key(fingerprint) as key:
                _bytes += key.__bytearray__()
        return _bytes

    def __bytes__(self) -> bytes:
        """Return the public key block as bytes."""
        return bytes(self.__bytearray__())
