#!/usr/bin/env python3

from collections import namedtuple
import string
import sys

def printf(format, *args):
    print(format % args, end="")

BundledShader = namedtuple("BundledShader", "filename offset length")

def read_file(filename):
    with open(filename, "rb") as fp:
        return fp.read()

def main(argc, argv):
    shaders = []
    bundle = bytearray()

    for i in range(1, argc):
        contents = read_file(argv[i])
        shaders.append(BundledShader(argv[i], len(bundle), len(contents)))
        bundle += contents
    
    printf("// Autogenerated by make_bundled_shaders.py. Do not edit by hand!\n")
    printf("#include <string>\n")
    printf("#include \"bundled_shaders.h\"\n")
    printf("\n")
    printf("namespace movit {\n")
    printf("\n")
    printf("BundledShader bundled_shaders[] = {\n")
    for shader in shaders:
        printf("\t{ \"%s\", %u, %u },\n", shader.filename, shader.offset, shader.length)
    printf("\t{ nullptr, 0, 0 }\n")
    printf("};\n")
    printf("const char *shader_bundle = \"")
    for ch in bundle:
        ch = chr(ch)
        if ch == '\n':
            printf("\\n")
        elif ch == '\t':
            printf("\\t")
        elif ch == '"':
            printf("\\\"")
        elif ch == '\\':
            printf("\\\\")
        elif not ch in string.printable:
            printf("\\%o", ord(ch))
        else:
            printf("%c", ch)
    printf("\";\n")
    printf("\n")
    printf("}  // namespace movit\n")

if __name__ == '__main__':
    main(len(sys.argv), sys.argv)
