#!/usr/bin/env python3.9
# Copyright (c) 2020 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
# Use of this source is governed by Apache-2.0 License that can be found
# in the LICENSE file.

import os
import re
import subprocess
import sys
import urllib.request


HEADER_FILE = "/usr/include/sys/syscall.h"


def read_sysno(header_file):
    cmd = ["cc", "-E", "-dD", header_file]
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    out, err = p.communicate()
    if p.returncode != 0 or err:
        print(err)
        sys.exit(1)
    return parse_sysno(out.decode())


def parse_sysno(content):
    sysnum_pattern = re.compile("^#define\s+SYS_([a-z_0-9]+)\s+(\d+)$")

    lines = [
        "",
        "// Code generated by mksysnum_netbsd.py; DO NOT EDIT.",
        "",
        "use crate::syscalls::Sysno;",
        "",
    ]
    names = []

    for line in content.split("\n"):
        if not line:
            continue
        m = sysnum_pattern.match(line)
        if m:
            name = m.group(1)
            num = m.group(2)

            line = "pub const SYS_{0}: Sysno = {1};".format(name.upper(), num)
            names.append(name)
            lines.append(line)
    return (lines, names)


def rust_fmt(filename):
    subprocess.run(["rustfmt", filename])


def main():
    if len(sys.argv) != 2:
        print("Usage: %s arch" % sys.argv[0])
        sys.exit(1)

    arch_name = sys.argv[1]
    platform_folder = os.path.join("platform", "netbsd-%s" % arch_name)

    lines, names = read_sysno(HEADER_FILE)
    sysnum_file = os.path.join(platform_folder, "sysno.rs")
    with open(sysnum_file, "w") as fh:
        fh.write("\n".join(lines))
    rust_fmt(sysnum_file)

if __name__ == "__main__":
    main()
