#!/usr/bin/env python3
# GStreamer
# Copyright (C) 2023 Seungha Yang <seungha@centricular.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301, USA.

import sys
import os
import argparse

start_header = """/*
 * This file is autogenerated by collect_hlsl_header.py
 */
#pragma once

"""

start_map = """
#define MAKE_BYTECODE(name) { G_STRINGIFY (name), { g_##name, sizeof (g_##name)} }
static std::unordered_map<std::string, std::pair<const BYTE *, SIZE_T>>
"""

end_map = """};
#undef MAKE_BYTECODE
"""

def main(args):
    parser = argparse.ArgumentParser(description='Read precompiled HLSL headers from directory and make single header')
    parser.add_argument("--input", help="the precompiled HLSL header directory")
    parser.add_argument("--output", help="output header file location")
    parser.add_argument("--prefix", help="HLSL header filename prefix")
    parser.add_argument("--name", help="Hash map variable name")
    args = parser.parse_args(args)

    # Scan precompiled PSMain_*.h headers in build directory
    # and generate single header
    hlsl_headers = [os.path.basename(file) for file in os.listdir(args.input) if file.startswith(args.prefix) and file.endswith(".h") ]

    with open(args.output, 'w', newline='\n', encoding='utf8') as f:
        f.write(start_header)
        for file in hlsl_headers:
            f.write("#include \"")
            f.write(file)
            f.write("\"\n")
        f.write(start_map)
        f.write(args.name)
        f.write(" = {\n")
        for file in hlsl_headers:
            f.write("  MAKE_BYTECODE ({}),\n".format(os.path.splitext(file)[0]))
        f.write(end_map)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
