const std = @import("std");

/// Sync local directory to remote via rsync over SSH
pub fn sync(allocator: std.mem.Allocator, local_path: []const u8, remote_path: []const u8, ssh_port: u16) !void {
    const port_str = try std.fmt.allocPrint(allocator, "{d}", .{ssh_port});
    defer allocator.free(port_str);

    const ssh_opt = try std.fmt.allocPrint(allocator, "ssh -p {s}", .{port_str});
    defer allocator.free(ssh_opt);

    // Build rsync command: rsync -avz -e "ssh -p PORT" local/ remote/
    var child = std.process.Child.init(
        &[_][]const u8{
            "rsync",
            "-avz",
            "--delete",
            "-e",
            ssh_opt,
            local_path,
            remote_path,
        },
        allocator,
    );

    child.stdin_behavior = .Ignore;
    child.stdout_behavior = .Inherit;
    child.stderr_behavior = .Inherit;

    const term = try child.spawnAndWait();

    switch (term) {
        .Exited => |code| {
            if (code != 0) {
                std.debug.print("rsync failed with exit code {d}\n", .{code});
                return error.RsyncFailed;
            }
        },
        .Signal => {
            return error.RsyncKilled;
        },
        else => {
            return error.RsyncUnknownError;
        },
    }
}
