#=========================== begin_copyright_notice ============================
#
# Copyright (C) 2017-2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
#============================ end_copyright_notice =============================

import binascii
import os
import re
import sys




def PrintHelp():
    sys.stdout.write('Usage: {0} <input file> <output file> <symbol name> <attribute>\n'.format(os.path.basename(__file__)))
    sys.stdout.write('\n')
    sys.stdout.write('    <input file>  - Path to input file which will be embedded.\n')
    sys.stdout.write('    <output file> - Path to output .cpp file which embedded data\n')
    sys.stdout.write('                    will be written to.\n')
    sys.stdout.write('    <symbol name> - Base name of symbol which identifies embedded data.\n')
    sys.stdout.write('    <attribute>   - "visibility" to add visibility attribute, "no_attr" to add no attribute\n')



symRe     = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
lineSize  = 20
chunkSize = 131072



numArgs = 5
if len(sys.argv) < numArgs:
    PrintHelp()
    exit(0)
for arg in sys.argv:
    if arg == '-h' or arg == '--help':
        PrintHelp()
        exit(0)
if len(sys.argv) > numArgs:
    sys.stderr.write('WARNING: Number of arguments is greater than number of supported arguments.\n')
    sys.stderr.write('         All additional arguments will be ignored.\n')

symName = sys.argv[3].strip()
if not symRe.match(symName) or symName.endswith('_size'):
    sys.stderr.write('ERROR: Invalid symbol name "{0}".\n'.format(symName))
    exit(1)

attrOpt = sys.argv[4].strip()
if attrOpt == "visibility":
    attr = '__attribute__((visibility("default")))'
elif attrOpt == "no_attr":
    attr = ""
else:
    sys.stderr.write('ERROR: Invalid attribute argument: "{0}".\n'.format(attrOpt))
    exit(1)

try:
    openedFiles = list()

    try:
        inFile = open(sys.argv[1], 'rb')
    except EnvironmentError as ex:
        sys.stderr.write('ERROR: Cannot open input file "{0}".\n       {1}.\n'.format(sys.argv[1], ex.strerror))
        exit(1)
    openedFiles.append(inFile)


    try:
        outFile = open(sys.argv[2], 'w')
    except EnvironmentError as ex:
        sys.stderr.write('ERROR: Cannot create/open output file "{0}".\n       {1}.\n'.format(sys.argv[2], ex.strerror))
        exit(1)
    openedFiles.append(outFile)

    outFile.write('// This file is auto generated by resource_embedder, DO NOT EDIT\n\n')
    outFile.write('unsigned char {0} {1}[] = {{'.format(attr, symName))

    embeddedSize = 0;
    readBytes = inFile.read(chunkSize)
    while len(readBytes) > 0:
        readSize = len(readBytes)
        hexBytes = binascii.hexlify(readBytes)

        if embeddedSize > 0:
            outFile.write(',')
        outFile.write(','.join((('\n        0x' if (embeddedSize + i) % lineSize == 0 else ' 0x') + hexBytes[2*i:2*i+2].decode("utf-8")) for i in range(readSize)))

        embeddedSize += readSize
        readBytes = inFile.read(chunkSize)

    outFile.write('\n    };\n\n');
    outFile.write('unsigned int {0} {1}_size = {2};\n\n'.format(attr, symName, embeddedSize))

except Exception as ex:
    sys.stderr.write('ERROR: Unknown error.\n       {0}.\n'.format(repr(ex)))
    for openedFile in openedFiles:
        openedFile.close()
    exit(1)
finally:
    for openedFile in openedFiles:
        openedFile.close()
