# SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2022-2023 Texas Instruments Incorporated - https://www.ti.com/
# Written by Neha Malcom Francis <n-francis@ti.com>
#

# Support for generation of TI secured binary blobs

from binman.entry import EntryArg
from binman.etype.x509_cert import Entry_x509_cert

from dtoc import fdt_util

class Entry_ti_secure(Entry_x509_cert):
    """Entry containing a TI x509 certificate binary

    Properties / Entry arguments:
        - content: List of phandles to entries to sign
        - keyfile: Filename of file containing key to sign binary with
        - sha: Hash function to be used for signing

    Output files:
        - input.<unique_name> - input file passed to openssl
        - config.<unique_name> - input file generated for openssl (which is
          used as the config file)
        - cert.<unique_name> - output file generated by openssl (which is
          used as the entry contents)

    openssl signs the provided data, using the TI templated config file and
    writes the signature in this entry. This allows verification that the
    data is genuine.
    """
    def __init__(self, section, etype, node):
        super().__init__(section, etype, node)
        self.openssl = None

    def ReadNode(self):
        super().ReadNode()
        self.key_fname = self.GetEntryArgsOrProps([
            EntryArg('keyfile', str)], required=True)[0]
        self.sha = fdt_util.GetInt(self._node, 'sha', 512)
        self.req_dist_name = {'C': 'US',
                'ST': 'TX',
                'L': 'Dallas',
                'O': 'Texas Instruments Incorporated',
                'OU': 'Processors',
                'CN': 'TI Support',
                'emailAddress': 'support@ti.com'}

    def GetCertificate(self, required):
        """Get the contents of this entry

        Args:
            required: True if the data must be present, False if it is OK to
                return None

        Returns:
            bytes content of the entry, which is the certificate binary for the
                provided data
        """
        return super().GetCertificate(required=required, type='sysfw')

    def ObtainContents(self):
        data = self.data
        if data is None:
            data = self.GetCertificate(False)
        if data is None:
            return False
        self.SetContents(data)
        return True

    def ProcessContents(self):
        # The blob may have changed due to WriteSymbols()
        data = self.data
        return self.ProcessContentsUpdate(data)

    def AddBintools(self, btools):
        super().AddBintools(btools)
        self.openssl = self.AddBintool(btools, 'openssl')
