#!/usr/bin/env python3

"""
MPFS X509 DER to C Header converter

This script takes an X.509 DER file and converts it to a C header file
"""


#
#
# MPFS X509 DER to C Header converter
#
# Copyright 2021-2022 Microchip Corporation.
#
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
#
#
#

import argparse
import datetime
import os


def main():
    '''main function'''
    parser = argparse.ArgumentParser(description='X.509 DER to C header')
    parser.add_argument('--verbose', '-v', action='count', default=0)
    parser.add_argument('x509FileIn')
    parser.add_argument('cHeaderFileOut')
    global args
    args = parser.parse_args()

    if args.verbose:
        print('Reading from ' + args.x509FileIn)

    with open(args.x509FileIn, 'rb') as file_in:
        with open(args.cHeaderFileOut, 'w') as file_out:
            print('#ifndef HSS_ECDSA_PUBLIC_KEY_H',
                  '#define HSS_ECDSA_PUBLIC_KEY_H',
                  '',
                  '// automatically generated by %s' % (__file__),
                  '// %s'
                  % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
                  '',
                  'const char SECP384R1_ECDSA_public_key[] = {',
                  sep=os.linesep, file=file_out)

            byte = file_in.read(1)

            count = 0
            while byte:
                # do stuff
                if (count % 12) == 0:
                    print('    ', end='', file=file_out)

                print('0x%02X, ' % (byte[0]), end='', file=file_out)
                count += 1
                if (count % 12) == 0:
                    print('\n', end='', file=file_out)
                    count = 0
                byte = file_in.read(1)

            print('};', '', '#endif', sep=os.linesep, file=file_out)

#
#
#


if __name__ == '__main__':
    main()
