1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
const std = @import("std");
const zqlite = @import("zqlite");
const fuse = @cImport({
    @cDefine("_FILE_OFFSET_BITS", "64");
    @cDefine("FUSE_USE_VERSION", "25");
    @cInclude("fuse.h");
    @cInclude("fuse/fuse_opt.h");
    @cInclude("errno.h");
});

// Equivalent to Haskell's EnvReadOnly
const EnvReadMode = enum {
    read_only,
    read_write,
};

// File/directory entry types
const EntryType = enum {
    regular_file,
    directory,
};

// Result type for file info queries
const FileInfo = struct {
    content: []const u8,
    has_nested: bool,
};

const FileQueryResult = union(enum) {
    not_found,
    found: FileInfo,
};

// File handle state (equivalent to Haskell's State)
const FileState = struct {
    filename: []const u8,
    read_write: ReadWriteMode,

    const Self = @This();

    pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
        allocator.free(self.filename);
    }
};

// Read/write mode for individual files (equivalent to Haskell's ReadWrite)
const ReadWriteMode = enum {
    write_only,
    read_write,
    read_only,
};

// Bitfields from C struct fuse_file_info (packed into u32, lowest bit first)
const FuseFileInfoBitfields = packed struct(u32) {
    direct_io: u1,
    keep_cache: u1,
    flush: u1,
    nonseekable: u1,
    flock_release: u1,
    padding: u27,
};

// Zig equivalent of C struct fuse_file_info from fuse_common.h
const FuseFileInfo = extern struct {
    flags: c_int,
    fh_old: c_ulong,
    writepage: c_int,
    bitfields: FuseFileInfoBitfields,
    fh: u64,
};

// Application state passed to all FUSE operations
const AppState = struct {
    conn: zqlite.Conn,
    read_mode: EnvReadMode,
    allocator: std.mem.Allocator,

    const Self = @This();

    pub fn init(allocator: std.mem.Allocator, db_path: []const u8) !Self {
        // Convert to null-terminated string for zqlite
        const db_path_z = try allocator.dupeZ(u8, db_path);
        defer allocator.free(db_path_z);
        const conn = try zqlite.Conn.init(db_path_z, zqlite.c.SQLITE_OPEN_CREATE | zqlite.c.SQLITE_OPEN_READWRITE);

        // Set busy timeout to handle concurrent access
        try conn.busyTimeout(5000); // 5 second timeout

        // Default to read-write, we'll determine actual mode based on table type
        return Self{
            .conn = conn,
            .read_mode = .read_write,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *Self) void {
        self.conn.close();
    }
};

// Global state for FUSE operations (necessary due to C API limitations)
var g_app_state: ?*AppState = null;

// FUSE callback implementations
fn fuse_getattr(path: [*c]const u8, stbuf: [*c]fuse.struct_stat) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.ENOENT;
    const path_slice = cStrToSlice(path);
    std.debug.print("fuse_getattr: {s}\n", .{path_slice});

    // Special case for root directory
    if (std.mem.eql(u8, path_slice, "/")) {
        std.debug.print("fuse_getattr: root directory\n", .{});
        fillFileStat(stbuf, state.read_mode, 0, .directory);
        return 0;
    }

    // Strip leading slash and query database
    const filename = stripLeadingSlash(path_slice);

    // Query for file content and check for nested files
    const file_info = queryFileInfo(state, filename) catch |err| {
        std.debug.print("fuse_getattr: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    switch (file_info) {
        .not_found => {
            // File not found in database, check if it's a directory prefix
            if (hasNestedFiles(state, filename)) |has_nested| {
                if (has_nested) {
                    std.debug.print("fuse_getattr: directory found (prefix): {s}\n", .{path_slice});
                    fillFileStat(stbuf, state.read_mode, 0, .directory);
                    return 0;
                }
            } else |err| {
                std.debug.print("fuse_getattr: database error checking nested: {}\n", .{err});
            }

            std.debug.print("fuse_getattr: file not found: {s}\n", .{path_slice});
            return -fuse.ENOENT;
        },
        .found => |info| {
            std.debug.print("fuse_getattr: file found: {s}\n", .{path_slice});
            const entry_type: EntryType = if (info.has_nested) .directory else .regular_file;
            fillFileStat(stbuf, state.read_mode, info.content.len, entry_type);
            return 0;
        },
    }
}

fn fuse_readdir(path: [*c]const u8, buf: ?*anyopaque, filler: fuse.fuse_fill_dir_t, offset: fuse.off_t, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.ENOENT;
    const path_slice = cStrToSlice(path);
    _ = fi;

    std.debug.print("fuse_readdir: {s} (offset: {})\n", .{ path_slice, offset });

    // Use FUSE readdir mode 1: ignore offset parameter, pass 0 to filler
    // This reads the whole directory in a single operation
    // If offset > 0, this is a continuation call - return no more entries
    if (offset > 0) {
        std.debug.print("fuse_readdir: offset > 0, no more entries\n", .{});
        return 0;
    }

    // Determine path parameter for SQL query
    const path_param = if (std.mem.eql(u8, path_slice, "/")) "" else stripLeadingSlash(path_slice);

    var file_count: usize = 0;
    var rows = state.conn.rows(
        \\SELECT filename, filecontent, COALESCE((SELECT 1 FROM files WHERE filename LIKE f.filename || '/%' LIMIT 1), 0) as has_nested
        \\FROM files f
        \\WHERE CASE
        \\  WHEN ? = '' THEN
        \\    -- Root directory: show files without slashes AND directories (files with exactly one slash)
        \\    (filename NOT LIKE '%/%' OR (filename LIKE '%/%' AND filename NOT LIKE '%/%/%'))
        \\  ELSE
        \\    -- Subdirectory: original logic
        \\    ((filename = ? OR filename LIKE ? || '/%') AND filename NOT LIKE ? || '/%/%')
        \\  END
        \\ORDER BY filename
    , .{ path_param, path_param, path_param, path_param }) catch |err| {
        std.debug.print("fuse_readdir: database error: {}\n", .{err});
        return -fuse.EIO;
    };
    defer rows.deinit();

    // Track which entries we've already added to avoid duplicates
    var seen_entries = std.ArrayList([]const u8).init(state.allocator);
    defer {
        for (seen_entries.items) |entry| {
            state.allocator.free(entry);
        }
        seen_entries.deinit();
    }

    // Process files immediately with no memory allocation needed
    while (rows.next()) |row| {
        const filename = row.get([]const u8, 0);

        // For directory listings, we need to extract the appropriate name for the display
        const display_name = if (std.mem.eql(u8, path_slice, "/")) blk: {
            // Root directory: check if filename contains a slash
            if (std.mem.indexOf(u8, filename, "/")) |slash_pos| {
                // Show only the directory name, not the full path
                break :blk filename[0..slash_pos];
            } else {
                // File without slash: show as-is
                break :blk filename;
            }
        } else blk: {
            // Non-root directory: strip the directory prefix from filenames
            const dir_path = stripLeadingSlash(path_slice);
            const prefix = std.fmt.allocPrint(state.allocator, "{s}/", .{dir_path}) catch {
                // Fallback on allocation error
                break :blk filename;
            };
            defer state.allocator.free(prefix);

            if (std.mem.startsWith(u8, filename, prefix)) {
                // Strip the directory prefix (e.g., "dir/file.txt" -> "file.txt")
                break :blk filename[prefix.len..];
            } else {
                // Fallback: show as-is
                break :blk filename;
            }
        };

        // Check if we've already added this entry
        var already_seen = false;
        for (seen_entries.items) |seen| {
            if (std.mem.eql(u8, seen, display_name)) {
                already_seen = true;
                break;
            }
        }

        if (already_seen) {
            std.debug.print("fuse_readdir: skipping duplicate: '{s}'\n", .{display_name});
            continue;
        }

        std.debug.print("fuse_readdir: adding file: '{s}' (display: '{s}')\n", .{ filename, display_name });

        // Remember this entry
        const entry_copy = state.allocator.dupe(u8, display_name) catch continue;
        seen_entries.append(entry_copy) catch {
            state.allocator.free(entry_copy);
            continue;
        };

        // Convert to null-terminated string for FUSE
        const filename_z = state.allocator.dupeZ(u8, display_name) catch continue;
        defer state.allocator.free(filename_z);

        if (filler.?(buf, filename_z.ptr, null, 0) != 0) {
            std.debug.print("fuse_readdir: filler returned error, stopping\n", .{});
            return -fuse.EIO;
        }
        file_count += 1;
    }

    std.debug.print("fuse_readdir: listed {} files in {s}\n", .{ file_count, path_slice });
    return 0;
}

fn fuse_open(path: [*c]const u8, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.ENOENT;
    const path_slice = cStrToSlice(path);
    const file_info: *FuseFileInfo = @ptrCast(@alignCast(fi orelse return -fuse.EIO));

    std.debug.print("fuse_open: {s} (flags: 0x{X})\n", .{ path_slice, file_info.flags });

    // Check for unsupported flags (equivalent to Haskell's flag validation)
    const unsupported_flags = file_info.flags & ~@as(c_int, fuse.O_ACCMODE);
    if (unsupported_flags != 0) {
        std.debug.print("WARN fuse_open: unsupported flags: 0x{X} (access mode: {})\n", .{ unsupported_flags, file_info.flags & fuse.O_ACCMODE });
    }

    // Determine read/write mode based on app state and open mode
    const open_mode = file_info.flags & fuse.O_ACCMODE;
    const read_write_mode = determineReadWriteMode(state.read_mode, open_mode);

    // Strip leading slash and check if file exists
    const filename = stripLeadingSlash(path_slice);
    const file_exists = fileExists(state, filename) catch |err| {
        std.debug.print("fuse_open: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    if (!file_exists) {
        std.debug.print("fuse_open: file not found: {s}\n", .{path_slice});
        return -fuse.ENOENT;
    }

    // Create file state and store in file handle
    const file_state = state.allocator.create(FileState) catch {
        return -fuse.ENOMEM;
    };

    // Store a copy of the filename
    const filename_copy = state.allocator.dupe(u8, filename) catch {
        state.allocator.destroy(file_state);
        return -fuse.ENOMEM;
    };

    file_state.* = FileState{
        .filename = filename_copy,
        .read_write = read_write_mode,
    };

    // Store pointer to file state in FUSE file handle
    file_info.fh = @intFromPtr(file_state);

    const bitfield_value = @as(u32, @bitCast(file_info.bitfields));
    std.debug.print("fuse_open: file opened successfully: {s} (bitfields: 0x{X})\n", .{ path_slice, bitfield_value });
    return 0;
}

fn fuse_read(path: [*c]const u8, buf: [*c]u8, size: usize, offset: fuse.off_t, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);
    const file_info: *FuseFileInfo = @ptrCast(@alignCast(fi orelse return -fuse.EIO));

    std.debug.print("fuse_read: {s} (size: {}, offset: {})\n", .{ path_slice, size, offset });

    // Get the FileState from the file handle
    const file_state: *FileState = @ptrFromInt(file_info.fh);

    if (offset < 0) {
        return 0; // Invalid offset
    }

    // Read data from database using SQL SUBSTR
    const read_data = readFileContentAtOffset(state, file_state.filename, @intCast(offset), size) catch |err| {
        std.debug.print("fuse_read: database error: {}\n", .{err});
        return -fuse.EIO;
    };
    defer state.allocator.free(read_data);

    // Copy the data to the buffer
    const bytes_to_read = @min(size, read_data.len);
    if (bytes_to_read > 0) {
        @memcpy(buf[0..bytes_to_read], read_data[0..bytes_to_read]);
    }

    std.debug.print("fuse_read: read {} bytes from offset {}\n", .{ bytes_to_read, offset });
    return @intCast(bytes_to_read);
}

fn fuse_write(path: [*c]const u8, buf: [*c]const u8, size: usize, offset: fuse.off_t, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);
    const file_info: *FuseFileInfo = @ptrCast(@alignCast(fi orelse return -fuse.EIO));

    std.debug.print("fuse_write: {s} (size: {}, offset: {})\n", .{ path_slice, size, offset });

    // Get the FileState from the file handle
    const file_state: *FileState = @ptrFromInt(file_info.fh);

    // Check read/write mode - reject if read-only
    switch (file_state.read_write) {
        .read_only => {
            std.debug.print("fuse_write: cannot write to read-only file\n", .{});
            return -fuse.EROFS;
        },
        .write_only, .read_write => {
            // Continue with write operation
        },
    }

    if (offset < 0) {
        std.debug.print("fuse_write: invalid offset: {}\n", .{offset});
        return -fuse.EINVAL;
    }

    // Get the data to write as a slice
    const write_data = buf[0..size];

    // Write data to database using SQL substring operations
    writeFileContentAtOffset(state, file_state.filename, @intCast(offset), write_data) catch |err| {
        std.debug.print("fuse_write: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    std.debug.print("fuse_write: wrote {} bytes at offset {}\n", .{ size, offset });
    return @intCast(size);
}

fn fuse_create(path: [*c]const u8, mode: fuse.mode_t, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);
    const file_info: *FuseFileInfo = @ptrCast(@alignCast(fi orelse return -fuse.EIO));

    std.debug.print("fuse_create: {s} (mode: 0o{o}, flags: 0x{X})\n", .{ path_slice, mode, file_info.flags });

    // Determine read/write mode based on app state and open flags
    const open_mode = file_info.flags & fuse.O_ACCMODE;
    const read_write_mode = determineReadWriteMode(state.read_mode, open_mode);

    // Strip leading slash and create empty file in database
    const filename = stripLeadingSlash(path_slice);
    const empty_content: []const u8 = "";
    updateFileContent(state, filename, empty_content) catch |err| {
        std.debug.print("fuse_create: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    // Create file state
    const file_state = state.allocator.create(FileState) catch {
        return -fuse.ENOMEM;
    };

    // Store a copy of the filename
    const filename_copy = state.allocator.dupe(u8, filename) catch {
        state.allocator.destroy(file_state);
        return -fuse.ENOMEM;
    };

    file_state.* = FileState{
        .filename = filename_copy,
        .read_write = read_write_mode,
    };

    // Store pointer to file state in FUSE file handle
    file_info.fh = @intFromPtr(file_state);

    std.debug.print("fuse_create: file created successfully: {s}\n", .{path_slice});
    return 0;
}

fn fuse_unlink(path: [*c]const u8) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);

    std.debug.print("fuse_unlink: {s}\n", .{path_slice});

    // Strip leading slash and delete file from database
    const filename = stripLeadingSlash(path_slice);
    deleteFile(state, filename) catch |err| {
        std.debug.print("fuse_unlink: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    std.debug.print("fuse_unlink: file deleted successfully: {s}\n", .{path_slice});
    return 0;
}

fn fuse_truncate(path: [*c]const u8, length: fuse.off_t) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);

    std.debug.print("fuse_truncate: {s} (length: {})\n", .{ path_slice, length });

    if (length < 0) {
        std.debug.print("fuse_truncate: invalid length: {}\n", .{length});
        return -fuse.EINVAL;
    }

    // Strip leading slash and check if file exists
    const filename = stripLeadingSlash(path_slice);
    const file_exists_result = fileExists(state, filename) catch |err| {
        std.debug.print("fuse_truncate: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    if (!file_exists_result) {
        std.debug.print("fuse_truncate: file not found: {s}\n", .{path_slice});
        return -fuse.ENOENT;
    }

    const truncate_length = @as(usize, @intCast(length));

    // Truncate using SQL operations
    truncateFileContent(state, filename, truncate_length) catch |err| {
        std.debug.print("fuse_truncate: database error: {}\n", .{err});
        return -fuse.EIO;
    };

    std.debug.print("fuse_truncate: file truncated successfully: {s} to {} bytes\n", .{ path_slice, truncate_length });
    return 0;
}

fn fuse_flush(path: [*c]const u8, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const path_slice = cStrToSlice(path);
    _ = fi;

    std.debug.print("fuse_flush: {s}\n", .{path_slice});
    // In our implementation, all writes are immediately committed to the database
    // so flush is a no-op
    return 0;
}

fn fuse_fsync(path: [*c]const u8, datasync: c_int, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const path_slice = cStrToSlice(path);
    _ = fi;

    std.debug.print("fuse_fsync: {s} (datasync: {})\n", .{ path_slice, datasync });
    // In our implementation, all writes are immediately committed to the database
    // so fsync is a no-op
    return 0;
}

fn fuse_release(path: [*c]const u8, fi: ?*fuse.struct_fuse_file_info) callconv(.C) c_int {
    const state = g_app_state orelse return -fuse.EIO;
    const path_slice = cStrToSlice(path);
    const file_info: *FuseFileInfo = @ptrCast(@alignCast(fi orelse return -fuse.EIO));

    std.debug.print("fuse_release: {s}\n", .{path_slice});

    // Clean up the FileState
    if (file_info.fh != 0) {
        const file_state: *FileState = @ptrFromInt(file_info.fh);
        file_state.deinit(state.allocator);
        state.allocator.destroy(file_state);
        file_info.fh = 0;
    }

    std.debug.print("fuse_release: file closed successfully: {s}\n", .{path_slice});
    return 0;
}

fn fuse_init() callconv(.C) ?*anyopaque {
    std.debug.print("FUSE_INIT_COMPLETE\n", .{});
    return null;
}

const fuse_operations = fuse.fuse_operations_compat25{
    .getattr = fuse_getattr,
    .readdir = fuse_readdir,
    .open = fuse_open,
    .read = fuse_read,
    .write = fuse_write,
    .create = fuse_create,
    .unlink = fuse_unlink,
    .truncate = fuse_truncate,
    .flush = fuse_flush,
    .fsync = fuse_fsync,
    .release = fuse_release,
    .init = fuse_init,
    .destroy = null,
    .access = null,
};

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Get command line arguments
    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    // Find -- separator in command line
    var dash_dash_index: ?usize = null;
    for (args, 0..) |arg, i| {
        if (std.mem.eql(u8, arg, "--")) {
            dash_dash_index = i;
            break;
        }
    }

    // Determine database path based on -- presence
    const database_path = if (dash_dash_index) |dd_idx| blk: {
        if (dd_idx + 1 < args.len) {
            break :blk args[dd_idx + 1];
        } else {
            std.debug.panic("Error: -- found but no database path argument follows\n", .{});
        }
    } else blk: {
        if (args.len > 1) {
            break :blk args[args.len - 1];
        } else {
            std.debug.panic("Error: No database path provided. Usage: sqlitefs [options] mountpoint [-- dbpath] or sqlitefs [options] mountpoint dbpath\n", .{});
        }
    };

    std.debug.print("Using database path: {s}\n", .{database_path});

    // Remove database path and -- from argv for FUSE
    var filtered_args = std.ArrayList([:0]u8).init(allocator);
    defer filtered_args.deinit();

    for (args) |arg| {
        // Skip the database path and -- separator
        if (std.mem.eql(u8, arg, database_path) and !std.mem.eql(u8, arg, args[0])) {
            // Don't add database path (unless it's the program name)
            continue;
        }
        if (std.mem.eql(u8, arg, "--")) {
            // Don't add -- separator
            continue;
        }
        try filtered_args.append(arg);
    }

    // Initialize app state with database connection
    var app_state = try AppState.init(allocator, database_path);
    defer app_state.deinit();

    // Determine if table exists and its type (mirroring Haskell logic)
    const table_name = "files";
    const table_info = try checkTableType(&app_state, table_name);

    switch (table_info) {
        .not_found => {
            std.debug.print("No table named '{s}' exists, creating it\n", .{table_name});
            try createFilesTable(&app_state);
            std.debug.print("Table '{s}' created successfully, mounting read-write\n", .{table_name});
            app_state.read_mode = .read_write;
            
            // Enable WAL mode for better concurrency in read-write mode
            app_state.conn.exec("PRAGMA journal_mode=WAL", .{}) catch |err| {
                std.debug.print("Warning: Failed to enable WAL mode: {}\n", .{err});
                std.debug.print("Continuing with default journal mode\n", .{});
            };
        },
        .view => {
            std.debug.print("Table '{s}' is a view, mounting read-only\n", .{table_name});
            app_state.read_mode = .read_only;
        },
        .table => {
            std.debug.print("Table '{s}' is a table, mounting read-write\n", .{table_name});
            app_state.read_mode = .read_write;
            
            // Enable WAL mode for better concurrency in read-write mode
            app_state.conn.exec("PRAGMA journal_mode=WAL", .{}) catch |err| {
                std.debug.print("Warning: Failed to enable WAL mode: {}\n", .{err});
                std.debug.print("Continuing with default journal mode\n", .{});
            };
        },
        .unknown => |type_name| {
            std.debug.print("Table '{s}' is of unknown type '{s}', mounting read-only\n", .{ table_name, type_name });
            app_state.read_mode = .read_only;
        },
    }

    // Set global state for FUSE operations
    g_app_state = &app_state;

    // Convert filtered args to C format for FUSE
    var c_args = try allocator.alloc([*c]u8, filtered_args.items.len);
    defer allocator.free(c_args);

    for (filtered_args.items, 0..) |arg, i| {
        c_args[i] = @constCast(@ptrCast(arg.ptr));
    }

    // Start FUSE filesystem with filtered arguments
    _ = fuse.fuse_main_real_compat25(@intCast(filtered_args.items.len), c_args.ptr, &fuse_operations, @sizeOf(fuse.fuse_operations_compat25));
}

const TableInfo = union(enum) {
    not_found,
    view,
    table,
    unknown: []const u8,
};

fn checkTableType(app_state: *AppState, table_name: []const u8) !TableInfo {
    // Query sqlite_schema to determine table type (equivalent to Haskell query)
    var rows = try app_state.conn.rows("SELECT name, type FROM sqlite_schema WHERE name = ?", .{table_name});
    defer rows.deinit();

    if (rows.next()) |row| {
        const type_str = row.get([]const u8, 1);

        if (std.mem.eql(u8, type_str, "view")) {
            return .view;
        } else if (std.mem.eql(u8, type_str, "table")) {
            return .table;
        } else {
            // Allocate copy of type string since row data is temporary
            const type_copy = try app_state.allocator.dupe(u8, type_str);
            return TableInfo{ .unknown = type_copy };
        }
    } else {
        return .not_found;
    }
}

// Combined query for file content and nested file detection (equivalent to Haskell's myFuseGetFileStat query)
fn queryFileInfo(app_state: *AppState, filename: []const u8) !FileQueryResult {
    var rows = try app_state.conn.rows(
        \\SELECT filecontent, (SELECT 1 FROM files WHERE filename LIKE ? || '/%' LIMIT 1) as has_nested
        \\FROM files
        \\WHERE filename = ?
        \\LIMIT 1
    , .{ filename, filename });
    defer rows.deinit();

    if (rows.next()) |row| {
        const content = row.get([]const u8, 0);
        const has_nested_raw = row.get(?i64, 1);
        const has_nested = has_nested_raw != null;

        // Make a copy since row data is temporary
        const content_copy = try app_state.allocator.dupe(u8, content);

        return FileQueryResult{ .found = FileInfo{
            .content = content_copy,
            .has_nested = has_nested,
        } };
    }

    return .not_found;
}

// Helper function to query file content from database (kept for compatibility)
fn queryFileContent(app_state: *AppState, filename: []const u8) !?[]const u8 {
    var rows = try app_state.conn.rows("SELECT filecontent FROM files WHERE filename = ?", .{filename});
    defer rows.deinit();

    if (rows.next()) |row| {
        const content = row.get([]const u8, 0);
        // Make a copy since row data is temporary
        return try app_state.allocator.dupe(u8, content);
    }

    return null;
}

// Helper function to check if path has nested files (is a directory)
fn hasNestedFiles(app_state: *AppState, path: []const u8) !bool {
    const pattern = try std.fmt.allocPrint(app_state.allocator, "{s}/%", .{path});
    defer app_state.allocator.free(pattern);

    var rows = try app_state.conn.rows("SELECT 1 FROM files WHERE filename LIKE ? LIMIT 1", .{pattern});
    defer rows.deinit();

    return rows.next() != null;
}

// Helper function to update file content in database (equivalent to Haskell's myFuseWrite SQL)
fn updateFileContent(app_state: *AppState, filename: []const u8, content: []const u8) !void {
    try app_state.conn.exec(
        \\INSERT INTO files (filename, filecontent) VALUES (?, ?)
        \\ON CONFLICT(filename) DO UPDATE SET filecontent = ?
    , .{ filename, content, content });
}

// Helper function to delete file from database (equivalent to Haskell's myFuseRemoveLink SQL)
fn deleteFile(app_state: *AppState, filename: []const u8) !void {
    try app_state.conn.exec("DELETE FROM files WHERE filename = ?", .{filename});
}

// Helper function to check if file exists in database
fn fileExists(app_state: *AppState, filename: []const u8) !bool {
    var rows = try app_state.conn.rows("SELECT 1 FROM files WHERE filename = ? LIMIT 1", .{filename});
    defer rows.deinit();

    return rows.next() != null;
}

// Helper function to read file content at specific offset using SQL SUBSTR
fn readFileContentAtOffset(app_state: *AppState, filename: []const u8, offset: usize, size: usize) ![]u8 {
    // SQLite SUBSTR is 1-indexed, so offset+1
    var rows = try app_state.conn.rows("SELECT SUBSTR(filecontent, ?, ?) FROM files WHERE filename = ? LIMIT 1", .{ offset + 1, size, filename });
    defer rows.deinit();

    if (rows.next()) |row| {
        const content = row.get([]const u8, 0);
        // TODO: This truncates at the first null byte due to C string handling.
        // Files extended with ZEROBLOB will be truncated when read. Need to use
        // SQLite's blob API with explicit length (sqlite3_column_bytes) instead
        // of treating blob data as null-terminated strings.
        // Make a copy since row data is temporary
        return try app_state.allocator.dupe(u8, content);
    }

    // File not found or empty result - return empty slice
    return try app_state.allocator.alloc(u8, 0);
}

// Helper function to write file content at specific offset using SQL substring operations
fn writeFileContentAtOffset(app_state: *AppState, filename: []const u8, offset: usize, data: []const u8) !void {
    // Use SQL to concatenate: SUBSTR(content, 1, offset) + new_data + SUBSTR(content, offset+data_len+1)
    // SQLite SUBSTR is 1-indexed
    try app_state.conn.exec(
        \\UPDATE files SET filecontent =
        \\    SUBSTR(filecontent, 1, ?) || ? || SUBSTR(filecontent, ?)
        \\WHERE filename = ?
    , .{ offset, data, offset + data.len + 1, filename });
}

// Helper function to truncate file content using SQL operations
fn truncateFileContent(app_state: *AppState, filename: []const u8, new_length: usize) !void {
    if (new_length == 0) {
        // Truncate to empty
        try app_state.conn.exec("UPDATE files SET filecontent = '' WHERE filename = ?", .{filename});
    } else {
        // Truncate or extend using SQL SUBSTR and padding
        try app_state.conn.exec(
            \\UPDATE files SET filecontent =
            \\    CASE
            \\        WHEN LENGTH(filecontent) > ? THEN SUBSTR(filecontent, 1, ?)
            \\        ELSE filecontent || ZEROBLOB(? - LENGTH(filecontent))
            \\    END
            \\WHERE filename = ?
        , .{ new_length, new_length, new_length, filename });
    }
}

// Convert C string to Zig slice (helper for FUSE paths)
fn cStrToSlice(c_str: [*c]const u8) []const u8 {
    return std.mem.span(c_str);
}

// Create the files table if it doesn't exist (equivalent to Haskell's createTestTable)
fn createFilesTable(app_state: *AppState) !void {
    try app_state.conn.exec(
        \\CREATE TABLE IF NOT EXISTS files (
        \\  filename TEXT PRIMARY KEY,
        \\  filecontent BLOB
        \\)
    , .{});
}

// Strip leading slash from path (matching Haskell logic)
fn stripLeadingSlash(path: []const u8) []const u8 {
    if (path.len > 0 and path[0] == '/') {
        return path[1..];
    }
    return path;
}

// Determine read/write mode based on app state and open flags (equivalent to Haskell logic)
fn determineReadWriteMode(env_mode: EnvReadMode, open_mode: c_int) ReadWriteMode {
    switch (env_mode) {
        .read_write => {
            switch (open_mode) {
                fuse.O_RDONLY => {
                    std.debug.print("fuse_open: opening file in read-only mode on read-write file system\n", .{});
                    return .read_only;
                },
                fuse.O_WRONLY => {
                    std.debug.print("fuse_open: opening file in write-only mode on read-write file system\n", .{});
                    return .write_only;
                },
                fuse.O_RDWR => {
                    std.debug.print("fuse_open: opening file in read-write mode on read-write file system\n", .{});
                    return .read_write;
                },
                else => {
                    std.debug.print("fuse_open: unknown open mode {}, defaulting to read-only\n", .{open_mode});
                    return .read_only;
                },
            }
        },
        .read_only => {
            switch (open_mode) {
                fuse.O_RDONLY => {
                    std.debug.print("fuse_open: opening file in read-only mode on read-only file system\n", .{});
                    return .read_only;
                },
                fuse.O_WRONLY => {
                    std.debug.print("fuse_open: cannot open file in write-only mode on read-only file system\n", .{});
                    return .read_only;
                },
                fuse.O_RDWR => {
                    std.debug.print("fuse_open: cannot open file in read-write mode on read-only file system\n", .{});
                    return .read_only;
                },
                else => {
                    std.debug.print("fuse_open: unknown open mode {}, defaulting to read-only\n", .{open_mode});
                    return .read_only;
                },
            }
        },
    }
}

// Fill FUSE stat structure (equivalent to Haskell's fileStat function)
fn fillFileStat(stbuf: [*c]fuse.struct_stat, read_mode: EnvReadMode, file_size: usize, entry_type: EntryType) void {
    // Clear the stat buffer first
    @memset(@as([*]u8, @ptrCast(stbuf))[0..@sizeOf(fuse.struct_stat)], 0);

    // Set file type
    switch (entry_type) {
        .regular_file => stbuf.*.st_mode = fuse.S_IFREG,
        .directory => stbuf.*.st_mode = fuse.S_IFDIR,
    }

    // Set permissions based on read/write mode
    switch (read_mode) {
        .read_write => {
            stbuf.*.st_mode |= fuse.S_IRUSR | fuse.S_IWUSR | fuse.S_IRGRP | fuse.S_IWGRP | fuse.S_IROTH;
        },
        .read_only => {
            stbuf.*.st_mode |= fuse.S_IRUSR | fuse.S_IRGRP | fuse.S_IROTH;
        },
    }

    // Set file properties
    stbuf.*.st_nlink = 1;
    stbuf.*.st_size = @intCast(file_size);
    stbuf.*.st_blocks = @intCast((file_size + 511) / 512); // Round up to 512-byte blocks

    // TODO: Set timestamps - field names may vary by system
    // stbuf.*.st_atime = 0;
    // stbuf.*.st_mtime = 0;
    // stbuf.*.st_ctime = 0;
}

test "FuseFileInfoBitfields packing" {
    // Test that our packed struct matches C bitfield layout (little-endian bit order)
    var bitfields: FuseFileInfoBitfields = std.mem.zeroes(FuseFileInfoBitfields);

    // Test individual bits are in the correct positions
    bitfields.direct_io = 1;
    try std.testing.expectEqual(@as(u32, 0x1), @as(u32, @bitCast(bitfields)));

    bitfields = std.mem.zeroes(FuseFileInfoBitfields);
    bitfields.keep_cache = 1;
    try std.testing.expectEqual(@as(u32, 0x2), @as(u32, @bitCast(bitfields)));

    bitfields = std.mem.zeroes(FuseFileInfoBitfields);
    bitfields.flush = 1;
    try std.testing.expectEqual(@as(u32, 0x4), @as(u32, @bitCast(bitfields)));

    bitfields = std.mem.zeroes(FuseFileInfoBitfields);
    bitfields.nonseekable = 1;
    try std.testing.expectEqual(@as(u32, 0x8), @as(u32, @bitCast(bitfields)));

    bitfields = std.mem.zeroes(FuseFileInfoBitfields);
    bitfields.flock_release = 1;
    try std.testing.expectEqual(@as(u32, 0x10), @as(u32, @bitCast(bitfields)));
}