1#!/usr/local/bin/python3.8
2
3from __future__ import print_function
4import os
5import sys
6import binascii
7
8try:
9    from configparser import ConfigParser
10except ImportError:
11    from ConfigParser import SafeConfigParser as ConfigParser
12
13def file_byte_generator(filename):
14    with open(filename, "rb") as f:
15        block = f.read()
16        return block
17
18def eprint(*args, **kwargs):
19    print(*args, file=sys.stderr, **kwargs)
20
21def create_header(array_name, in_filename):
22    if sys.version_info >= (3,0):
23        hexified = ["0x" + binascii.hexlify(bytes([inp])).decode('ascii') for inp in file_byte_generator(in_filename)]
24    else:
25        hexified = ["0x" + binascii.hexlify(inp).decode('ascii') for inp in file_byte_generator(in_filename)]
26    print("const uint8_t " + array_name + "[] = {")
27    print(", ".join(hexified))
28    print("};")
29    return 0
30
31if __name__ == '__main__':
32    if len(sys.argv) < 3:
33        eprint('ERROR: usage: gen_cert_header.py array_name update_config_file')
34        sys.exit(1)
35
36    if not os.path.exists(sys.argv[2]):
37        eprint('The config file %s does not exist'%(sys.argv[2]))
38        sys.exit(1)
39
40    config = ConfigParser()
41    config.read(sys.argv[2])
42    sys.exit(create_header(sys.argv[1], config.get('Updater', 'certificate-der')))
43