#!/usr/bin/python

# This python script is used to convert image resources to C header files,
# so that they can be directly build within trustlet.
# This script must be called before build

import sys
import os
import re


sizes = []
arrays = []


def write_file(output, folder, f):

	with open("%s/%s" % (folder, f), "rb") as in_file:
		data = in_file.read()	

	output.write("uint8_t img_%s[] = {" % f.replace(".png", "").replace("-", "_"))
	output.write(', '.join(("0x%s" % byte.encode('hex')) for byte in data))
	output.write("};\n\n")

	arrays.append("img_%s" % f.replace(".png", "").replace("-", "_"))
	sizes.append(len(data))
			

def print_usage():
	print "Usage: python process_resource.py <resource mapping file> <resource folder> <output_header_file>"
	print
	print "NOTE: In each line of the resource mapping file, list the ID and its PNG image file name."
	print "For example:  'ID_PINPAD	    pinpad.png'."
	print "However, IDs will not be processed. It is only for convinience."
	print "We assume ID from the line number: first line has ID 0, second line has 1, and so on."
	print "If there is no resource, you must only put the ID. Empty lines will be skiped."

def main():
	if len(sys.argv) != 4:
		print_usage()

	mapping = sys.argv[1]
	folder = sys.argv[2]
	header = sys.argv[3]

	if not os.path.exists(mapping):
		print "Resource mapping file doesn't exist!" + mapping
		return
	if not os.path.isdir(folder):
		print "Resource folder doesn't exist!" + folder
		return

	pattern = re.compile("\s+")

	output = open("resource/%s" % header, "w")

	with open(mapping, "r") as in_file:
		for line in in_file:
			match = pattern.split(line)
			match = filter(lambda a: a != "", match)
			if len(match) == 0:
				print "Empty line found!"
				continue
			elif len(match) == 1:
				sizes.append(0)
				arrays.append("NULL")
				continue
			elif len(match) == 2:
				write_file(output, folder, match[1])
			else:
				print "Cannot process line: %s" % line
				print match
				return
			

	output.write("uint8_t* resource[%d] = {" % len(sizes))
	output.write(', '.join(arrays))
	output.write("};\n\n")

	output.write("uint32_t sizes[%d] = {" % len(sizes))
	output.write(', '.join(("%d" % s) for s in sizes))
	output.write("};\n\n")


	output.close()


if __name__ == "__main__":
    main()




