const std = @import("std");

pub fn build(b: *std.build.Builder) void {
    const use_elixir = b.option(bool, "use-elixir", "Whether to compile for elixir or erlang (default)") orelse false;

    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const erl_out = std.ChildProcess.exec(.{
        .allocator = allocator,
        .argv = &.{
            "erl",
            "-noshell",
            "-eval", "io:format(\"~ts/erts-~ts/include/\", [code:root_dir(), erlang:system_info(version)]).",
            "-s", "init", "stop"
        }
    }) catch unreachable;
    const erl_include = erl_out.stdout;
    std.log.debug("erl_include: {s}", .{erl_include});

    // Standard target options allows the person running `zig build` to choose
    // what target to build for. Here we do not override the defaults, which
    // means any target is allowed, and the default is native. Other options
    // for restricting supported target set are available.
    const target = b.standardTargetOptions(.{});

    // Standard release options allow the person running `zig build` to select
    // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
    const mode = b.standardReleaseOptions();

    const lib_name = if(use_elixir) "proj_nif_ex" else "proj_nif";

    const lib = b.addSharedLibrary(
        lib_name,
        "proj_nif.zig",
        .unversioned
    );
    const lib_options = b.addOptions();
    lib_options.addOption(bool, "use_elixir", use_elixir);
    lib.addPackage(lib_options.getPackage("build_options"));

    lib.addSystemIncludeDir(erl_include);
    lib.linkLibC();
    lib.linkSystemLibrary("proj");
    lib.setTarget(target);
    lib.setBuildMode(mode);
    lib.install();
}
