From 6d8710545ed13da1f75c3e331a3724cef958134a Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Sun, 12 May 2024 03:30:36 +0500 Subject: [PATCH] Add etc hosts replication --- src/hosts.zig | 37 +++++++++++++++++++++++++++++++++++-- src/main.zig | 4 ++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/hosts.zig b/src/hosts.zig index 8a74ea1..f452a94 100644 --- a/src/hosts.zig +++ b/src/hosts.zig @@ -1,6 +1,39 @@ const std = @import("std"); const util = @import("util.zig"); -pub fn update_hosts(ips: util.IP) !void { - std.debug.print("{}\n", .{ips}); +pub fn update_hosts(ip: util.IP) !void { + try create_tmp_hosts(ip); + try move_tmp_hosts(); } + +fn create_tmp_hosts(ip: util.IP) !void { + _ = ip; + + var old_hosts = try std.fs.openFileAbsolute("/etc/hosts", .{ .mode = .read_only }); + defer old_hosts.close(); + var tmp_hosts = try std.fs.createFileAbsolute("/tmp/hosts", .{ .truncate = true }); + defer tmp_hosts.close(); + + var buff = [_]u8{0x00} ** 50; + var buff_stream = std.io.fixedBufferStream(&buff); + const buff_reader = buff_stream.reader(); + const buff_writer = buff_stream.writer(); + var old_reader = old_hosts.reader(); + const tmp_writer = tmp_hosts.writer(); + + while (old_reader.streamUntilDelimiter(buff_writer, '\n', 50 - 1)) |_| { + var n = buff_stream.pos; + // do things to line + + buff[n] = '\n'; + n += 1; + buff_stream.pos = 0; + try buff_reader.streamUntilDelimiter(tmp_writer, '\n', 50); + try tmp_writer.writeByte('\n'); + buff_stream.pos = 0; + } else |_| { + // EOF + } +} + +fn move_tmp_hosts() !void {} diff --git a/src/main.zig b/src/main.zig index 3ac5f71..75f1815 100644 --- a/src/main.zig +++ b/src/main.zig @@ -6,6 +6,6 @@ const hosts = @import("hosts.zig"); pub fn main() !void { try util.check_perms(); const domain, const ip_ver = try util.get_input(); - const ips = try mdns.get_mdns(domain, ip_ver); - try hosts.update_hosts(ips); + const ip = try mdns.get_mdns(domain, ip_ver); + try hosts.update_hosts(ip); }