const std = @import("std");
const module = @import("../module.zig");

const gpa = std.heap.page_allocator;

fn cb() anyerror![]const u8 {
    var file = try std.fs.openFileAbsolute("/etc/os-release", .{});
    defer file.close();

    const contents = try file.readToEndAlloc(gpa, 1024); // read max 1024 bytes
    defer gpa.free(contents);

    var lines = std.mem.splitSequence(u8, contents, "\n");
    while (lines.next()) |line| {
        if (std.mem.startsWith(u8, line, "NAME=")) {
            // Strip 'NAME=' and optional quotes
            var name_line = line[5..];
            if (name_line.len >= 2 and name_line[0] == '"' and name_line[name_line.len - 1] == '"') {
                name_line = name_line[1..name_line.len - 1];
            }

            // Allocate copy to return
            const os_name = try gpa.alloc(u8, name_line.len);
            std.mem.copyForwards(u8, os_name, name_line);
            return os_name;
        }
    }

    return "Unknown OS";
}

pub const distro = module {
    .name = "distro",
    .prefix = "Distro: ",
    .callback = cb
};
