const std = @import("std");

pub fn build(b: *std.Build) !void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const enet_src = b.dependency("enet_src", .{});

    const lib = b.addLibrary(.{
        .name = "enet",
        .linkage = .static,
        .root_module = b.createModule(.{
            .target = target,
            .optimize = optimize,
        }),
    });

    var flags = try std.ArrayList([]const u8).initCapacity(b.allocator, 0);

    switch (target.result.os.tag) {
        .linux, .macos => {
            try flags.append(b.allocator, "-DHAS_FCNTL=1");
            try flags.append(b.allocator, "-DHAS_POLL=1");
            try flags.append(b.allocator, "-DHAS_GETADDRINFO=1");
            try flags.append(b.allocator, "-DHAS_GETNAMEINFO=1");
            try flags.append(b.allocator, "-DHAS_INET_PTON=1");
            try flags.append(b.allocator, "-DHAS_INET_NTOP=1");
            try flags.append(b.allocator, "-DHAS_MSGHDR_FLAGS=1");
        },
        else => {},
    }

    try flags.append(b.allocator, "-DHAS_OFFSETOF=1");
    try flags.append(b.allocator, "-DHAS_SOCKLEN_T=1");

    lib.root_module.addCSourceFiles(.{
        .root = enet_src.path(""),
        .files = &[_][]const u8{
            "callbacks.c",
            "compress.c",
            "host.c",
            "list.c",
            "packet.c",
            "peer.c",
            "protocol.c",
            "unix.c",
            "win32.c",
        },
        .flags = &[_][]const u8{
            "-DHAS_OFFSETOF=1",
            "-DHAS_SOCKLEN_T=1",
            "-DHAS_FCNTL=1",
            "-DHAS_POLL=1",
            "-DHAS_GETADDRINFO=1",
            "-DHAS_GETNAMEINFO=1",
            "-DHAS_INET_PTON=1",
            "-DHAS_INET_NTOP=1",
            "-DHAS_MSGHDR_FLAGS=1",
        }
    });


    if (target.result.os.tag == .windows) {
        lib.root_module.linkSystemLibrary("ws2_32", .{});
        lib.root_module.linkSystemLibrary("winmm", .{});
    }

    lib.root_module.addIncludePath(enet_src.path("include"));
    lib.root_module.link_libc = true;

    lib.installHeadersDirectory(enet_src.path("include/enet"), "enet", .{});

    b.installArtifact(lib);
}
