#!/usr/bin/env python3
# Copyright (c) 2019 Xu Shaohua <xushaohua2016@outlook.com>. All rights reserved.
# Use of this source is governed by General Public License that can be found
# in the LICENSE file.

import os
import re
import subprocess
import sys


def read_errno():
    cmd = ["gcc", "-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_errno(content):
    macro_pattern = re.compile("#define\s+(E\w+)\s+([A-Z0-9_]+)")
    lines = [
        "",
        "// Code generated by mkerrno_freebsd.py; DO NOT EDIT.",
        "",
        "pub type Errno = usize;",
        "",
    ]
    for line in content.split("\n"):
        m = macro_pattern.match(line)
        if m:
            line = "pub const {0}: Errno = {1};".format(m.group(1).upper(), m.group(2))
            lines.append(line)
    return lines


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

def write_errno(arch_name, lines):
    errno_file = os.path.join("platform", "freebsd-%s" % arch_name, "errno.rs")
    with open(errno_file, "w") as fh:
        fh.write("\n".join(lines))

    rust_fmt(errno_file)


def main():
    if len(sys.argv) < 2:
        print("Usage: %s arch-name" % sys.argv[0])
        sys.exit(1)
    arch_name = sys.argv[1]
    if arch_name == "-e":
        error_header_file = sys.argv[2]
        with open(error_header_file) as fh:
            content = fh.read()
            lines = parse_errno(content)
            print("\n".join(lines))
        return

    lines = read_errno()
    write_errno(arch_name, lines)


if __name__ == "__main__":
    main()
