1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-2.1-or-later
3
4import ast
5import os
6import re
7import sys
8
9import jinja2
10
11def parse_config_h(filename):
12    # Parse config.h file generated by meson.
13    ans = {}
14    for line in open(filename):
15        m = re.match(r'#define\s+(\w+)\s+(.*)', line)
16        if not m:
17            continue
18        a, b = m.groups()
19        if b and b[0] in '0123456789"':
20            b = ast.literal_eval(b)
21        ans[a] = b
22    return ans
23
24def render(filename, defines):
25    text = open(filename).read()
26    template = jinja2.Template(text, trim_blocks=True, undefined=jinja2.StrictUndefined)
27    return template.render(defines)
28
29if __name__ == '__main__':
30    defines = parse_config_h(sys.argv[1])
31    defines.update(parse_config_h(sys.argv[2]))
32    output = render(sys.argv[3], defines)
33    with open(sys.argv[4], 'w') as f:
34        f.write(output)
35        f.write('\n')
36    info = os.stat(sys.argv[3])
37    os.chmod(sys.argv[4], info.st_mode)
38