#!/usr/bin/env python3

import os
import argparse

def main():
    parser = argparse.ArgumentParser(description = 'Convert a binary file to a header.')
    parser.add_argument('--output', type = str, help = 'Path to header / C output.', required = True)
    parser.add_argument('--blob-name', type = str, help = 'Name of C buffer.', required = True)
    parser.add_argument('input', type = str, help = 'Input binary file.')
    args = parser.parse_args()

    if args.input is None:
        raise AssertionError('Need input file.')

    with open(args.input, 'rb') as f:
        buf = f.read()

    with open(args.output + '.h', 'w') as f:
        print('#pragma once', file = f)
        print('// Autogenerated by bin_to_text.py', file = f)
        print('#include <stdint.h>', file = f)
        print('#include <stddef.h>', file = f)
        print('#ifdef __cplusplus', file = f)
        print('extern "C" {', file = f)
        print('#endif', file = f)
        print('extern const uint8_t ' + args.blob_name + '[];', file = f)
        print('extern const size_t ' + args.blob_name + '_size;', file = f)
        print('#ifdef __cplusplus', file = f)
        print('}', file = f)
        print('#endif', file = f)

    with open(args.output + '.c', 'w') as f:
        print('// Autogenerated by bin_to_text.py', file = f)
        print('#include <' + os.path.basename(args.output) + '.h' + '>', file = f)
        print('const size_t ' + args.blob_name + '_size = ' + str(len(buf)) + ';', file = f)
        print('const uint8_t ' + args.blob_name + '[] = {', file = f)
        counter = 0
        for byte in buf:
            if counter == 0:
                print('\t', file = f, end = '')
            print(hex(byte) + ', ', end = '', file = f)
            counter += 1
            if counter == 16:
                counter = 0
                print('', file = f)
        if counter != 0:
            print('', file = f)
        print('};', file = f)

if __name__ == '__main__':
    main()