#===================== begin_copyright_notice ==================================

#Copyright (c) 2017 Intel Corporation

#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.


#======================= end_copyright_notice ==================================

import binascii
import os
import re
import sys




def PrintHelp():
    sys.stdout.write('Usage: {0} <input file> <output file> <symbol name>\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')



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



if len(sys.argv) < 4:
    PrintHelp()
    exit(0)
for arg in sys.argv:
    if arg == '-h' or arg == '--help':
        PrintHelp()
        exit(0)
if len(sys.argv) > 4:
    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)

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 __attribute__((visibility("default"))) {0}[] = {{'.format(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]) for i in xrange(readSize)))

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

    outFile.write('\n    };\n\n');
    outFile.write('unsigned int __attribute__((visibility("default"))) {0}_size = {1};\n\n'.format(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()
