#!/usr/bin/env python3

# Simple script to create a map of mnemonics names from standard
# system headers into their definitions. We use it to allow the
# use of such names in the "syscalls" filter in the config file.

import os
from collections import OrderedDict

mingw_prefix = os.getenv("MINGW_PREFIX", default="/msys64/mingw64")

definitions = OrderedDict()
for header in [
    "/usr/include/asm-generic/fcntl.h",
    "/usr/include/asm-generic/ioctls.h",
    "{}/x86_64-w64-mingw32/include/fcntl.h".format(mingw_prefix)]:
    if not os.path.exists(header):
        continue
    with open(header, "r") as f:
        for line in f.readlines():
            c_style_comments, cpp_style_comments = line.find("/*"), line.find("//")
            if c_style_comments >= 0:
                line = line[:c_style_comments]
            elif cpp_style_comments:
                line = line[:cpp_style_comments]

            parts = line.split()
            if line.startswith("#define") and len(parts) >= 3:
                if not parts[1].startswith("_"):
                    definitions[parts[1]] = "".join(parts[2:])

print("// Automatically generated by sysdefs_mapper.py")
print("#include <string>")
print("#include <map>\n")
print("#ifndef __MINGW64__")
print("# include <sys/ioctl.h>")
print("# include <fcntl.h>")
print("#endif\n")
print("static std::map<std::string, unsigned long> sysdefs = {")
for key, value in definitions.items():
    print(f'#ifdef {key}')
    print(f'    {{"{key}", {key}}},')
    print('#endif')
print("};")
