add_requires("python 3.x", {kind = "binary"})

add_rules("mode.debug", "mode.release")

set_languages("c++11")

target("elf++")
    set_kind("$(kind)")
    add_files("elf/*.cc")
    add_headerfiles("elf/elf++.hh", "elf/data.hh", "elf/common.hh", {prefixdir = "libelfin/elf"})

    on_load(function (target)
        local filename = "elf/to_string.cc"
        local file = io.open(filename, "w")
        file:print("// Automatically generated by xmake at " .. os.date("%y-%m-%d"))
        file:print("// DO NOT EDIT")
        file:print("")
        file:print([[#include "data.hh"]])
        file:print([[#include "to_hex.hh"]])
        file:print("")
        file:print("ELFPP_BEGIN_NAMESPACE")
        file:print("")

        local python = assert(import("lib.detect.find_tool")("python3"), "python not found!")
        local result = try { function()
            return os.iorunv(python.program,
                {"elf/enum-print.py", "-u", "--hex", "--no-type", "--mask", "shf", "--mask", "pf", "-x", "loos", "-x", "hios", "-x", "loproc", "-x", "hiproc"},
                {stdin = "elf/data.hh"})
        end }
        if result then
            file:print(result)
        end

        file:print("ELFPP_END_NAMESPACE")
        file:close()
        target:add("files", path.join(os.projectdir(), filename))
    end)

target("dwarf++")
    set_kind("$(kind)")
    add_files("dwarf/*.cc")
    add_headerfiles("dwarf/dwarf++.hh", "dwarf/data.hh", "dwarf/small_vector.hh", {prefixdir = "libelfin/dwarf"})

    on_load(function (target)
        local filename = "dwarf/to_string.cc"
        local file = io.open(filename, "w")
        file:print("// Automatically generated by xmake at " .. os.date("%y-%m-%d"))
        file:print("// DO NOT EDIT")
        file:print("")
        file:print([[#include "internal.hh"]])
        file:print("")
        file:print("DWARFPP_BEGIN_NAMESPACE")
        file:print("")

        local python = assert(import("lib.detect.find_tool")("python3"), "python not found!")
        local result = try { function() return os.iorunv(python.program, {"elf/enum-print.py"}, {stdin = "dwarf/dwarf++.hh"}) end}
        if result then
            file:print(result)
        end

        result = try { function()
            return os.iorunv(python.program,
                {"elf/enum-print.py", "-s", "_", "-u", "--hex", "-x", "hi_user", "-x", "lo_user"},
                {stdin = "dwarf/data.hh"})
        end }
        if result then
            file:print(result)
        end

        file:print("DWARFPP_END_NAMESPACE")
        file:close()
        target:add("files", path.join(os.projectdir(), filename))
    end)
