1#!/usr/bin/env python3
2# Copyright (c) 2021, Arm Limited. All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5
6import argparse
7import uuid
8import zlib
9
10def main(metadata_file, img_type_uuids, location_uuids, img_uuids):
11    def add_field_to_metadata(value):
12        # Write the integer values to file in little endian representation
13        with open(metadata_file, "ab") as fp:
14            fp.write(value.to_bytes(4, byteorder='little'))
15
16    def add_uuid_to_metadata(uuid_str):
17        # Validate UUID string and write to file in little endian representation
18        uuid_val = uuid.UUID(uuid_str)
19        with open(metadata_file, "ab") as fp:
20            fp.write(uuid_val.bytes_le)
21
22    # Fill metadata preamble
23    add_field_to_metadata(1) #version=1
24    add_field_to_metadata(0) #active_index=0
25    add_field_to_metadata(0) #previous_active_index=0
26
27    for img_type_uuid, location_uuid in zip(img_type_uuids, location_uuids):
28        # Fill metadata image entry
29        add_uuid_to_metadata(img_type_uuid) # img_type_uuid
30        add_uuid_to_metadata(location_uuid) # location_uuid
31
32        for img_uuid in img_uuids:
33            # Fill metadata bank image info
34            add_uuid_to_metadata(img_uuid) # image unique bank_uuid
35            add_field_to_metadata(1)       # accepted=1
36            add_field_to_metadata(0)       # reserved (MBZ)
37
38    # Prepend CRC32
39    with open(metadata_file, 'rb+') as fp:
40        content = fp.read()
41        crc = zlib.crc32(content)
42        fp.seek(0)
43        fp.write(crc.to_bytes(4, byteorder='little') + content)
44
45if __name__ == "__main__":
46    parser = argparse.ArgumentParser()
47    parser.add_argument('--metadata_file', required=True,
48                        help='Output binary file to store the metadata')
49    parser.add_argument('--img_type_uuids', type=str, nargs='+', required=True,
50                        help='A list of UUIDs identifying the image types')
51    parser.add_argument('--location_uuids', type=str, nargs='+', required=True,
52                        help='A list of UUIDs of the storage volumes where the images are located. '
53                             'Must have the same length as img_type_uuids.')
54    parser.add_argument('--img_uuids', type=str, nargs='+', required=True,
55                        help='A list UUIDs of the images in a firmware bank')
56
57    args = parser.parse_args()
58
59    if len(args.img_type_uuids) != len(args.location_uuids):
60        parser.print_help()
61        raise argparse.ArgumentError(None, 'Arguments img_type_uuids and location_uuids must have the same length.')
62
63    main(args.metadata_file, args.img_type_uuids, args.location_uuids, args.img_uuids)
64