local sim = os.getenv("SIM") or "vcs"
local svparser_bin = "../bin/svparser"

target("TestSubModule")
    add_rules("verilua")

    if sim == "vcs" then
        add_toolchains("@vcs")
    else   
        add_toolchains("@verilator")
    end

    add_files("src/*.lua", "dut/*.v")

    set_values("cfg.top", "TestTop")
    set_values("cfg.lua_main", "src/LuaMain.lua")

    add_links("SubModule_vrtl")
    add_linkdirs("./SubModule_vrtl/target/release")

    add_values("verilator.flags", "+define+VIRTUAL_RTL")
    add_values("vcs.flags", "+define+VIRTUAL_RTL")

    before_build(function (target)
        local sourcefiles = target:sourcefiles()
        for i, file in ipairs(sourcefiles) do
            local target_module = "SubModule"
            local target_file = "SubModule.v"
            if file:endswith(target_file) then
                os.exec(svparser_bin .. " -f %s -m %s -od ./.vrtl", file, target_module)
                sourcefiles[i] = "./.vrtl/" .. target_file
            end
        end
        target:set("files", sourcefiles)
    end)

    add_runenvs("LD_LIBRARY_PATH", "./SubModule_vrtl/target/release")