const std = @import("std");
const linux = std.os.linux;

pub fn main() !void {
    std.log.debug("setting up watches.", .{});

    var event: linux.inotify_event = undefined;
    const event_buf = std.mem.asBytes(&event);

    const fd: i32 = @intCast(linux.inotify_init1(linux.IN.NONBLOCK));
    defer _ = linux.close(fd);

    const wd: i32 = @intCast(linux.inotify_add_watch(
        fd,
        "sample.txt",
        linux.IN.MODIFY | linux.IN.CLOSE_WRITE,
    ));
    defer _ = linux.inotify_rm_watch(fd, wd);

    var fds = [_]linux.pollfd{
        .{ .fd = fd, .events = linux.POLL.IN, .revents = 0 },
    };

    while (true) {
        const k = linux.poll(&fds, fds.len, 1000);
        std.log.debug("poll -> {d}", .{k});

        if (k > 0) {
            while (true) {
                const n: isize = @bitCast(linux.read(
                    fd,
                    event_buf.ptr,
                    event_buf.len,
                ));
                std.log.debug("read -> {d}", .{n});
                std.time.sleep(500 * std.time.ns_per_ms);
                if (n < 0) break;
            }
        }
    }
}
