const std = @import("std");

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

    const enet_real = b.dependency("enet_real", .{});
    const enet = b.createModule(.{
        .root_source_file = .{ .path = "src/enet.zig" },
        .target = target,
        .optimize = optimize,
        .link_libc = true,
        .sanitize_c = false,
    });
    enet.addCSourceFiles(.{
        .root = enet_real.path(""),
        .files = &.{
            "callbacks.c",
            "compress.c",
            "host.c",
            "list.c",
            "packet.c",
            "peer.c",
            "protocol.c",
            "unix.c",
            "win32.c",
        },
    });
    enet.addIncludePath(enet_real.path("include"));

    const client = b.addExecutable(.{
        .name = "client",
        .root_source_file = .{ .path = "src/client.zig" },
        .target = target,
        .optimize = optimize,
    });
    client.root_module.addImport("enet", enet);
    b.installArtifact(client);

    const server = b.addExecutable(.{
        .name = "server",
        .root_source_file = .{ .path = "src/server.zig" },
        .target = target,
        .optimize = optimize,
    });
    server.root_module.addImport("enet", enet);
    b.installArtifact(server);

    const client_cmd = b.addRunArtifact(client);
    client_cmd.step.dependOn(b.getInstallStep());
    const server_cmd = b.addRunArtifact(server);
    server_cmd.step.dependOn(b.getInstallStep());

    if (b.args) |args| {
        client_cmd.addArgs(args);
        server_cmd.addArgs(args);
    }

    const client_step = b.step("client", "Run the client");
    client_step.dependOn(&client_cmd.step);
    const server_step = b.step("server", "Run the server");
    server_step.dependOn(&server_cmd.step);

    const client_tests = b.addTest(.{
        .root_source_file = .{ .path = "src/client.zig" },
        .target = target,
        .optimize = optimize,
    });
    client_tests.root_module.addImport("enet", enet);
    const server_tests = b.addTest(.{
        .root_source_file = .{ .path = "src/server.zig" },
        .target = target,
        .optimize = optimize,
    });
    server_tests.root_module.addImport("enet", enet);

    const run_client_tests = b.addRunArtifact(client_tests);
    const run_server_tests = b.addRunArtifact(server_tests);

    const test_step = b.step("test", "Run tests");
    test_step.dependOn(&run_client_tests.step);
    test_step.dependOn(&run_server_tests.step);
}
