summaryrefslogtreecommitdiff
path: root/src/bin/store.zig
blob: 7eee8975ff807eadd8c69024ae9b15a28cb69262 (plain)
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
const std = @import("std");
const normalizeUser = @import("util.zig").normalizeUser;

const Self = @This();

maildir: std.Io.Dir,

pub fn init(io: std.Io, dir: []const u8) !Self {
    const maildir: std.Io.Dir = std.Io.Dir.openDirAbsolute(io, dir, .{}) catch |e| switch (e) {
        // First time startup, create the maildir
        error.FileNotFound => blk: {
            try std.Io.Dir.createDirAbsolute(io, dir, @fromBackingInt(@intCast(0o700)));
            break :blk try std.Io.Dir.openDirAbsolute(io, dir, .{});
        },
        else => return e,
    };
    maildir.createDirPath(io, "spool/queue") catch |e| switch (e) {
        error.PathAlreadyExists => {},
        else => return e,
    };
    maildir.createDirPath(io, "spool/active") catch |e| switch (e) {
        error.PathAlreadyExists => {},
        else => return e,
    };
    maildir.createDirPath(io, "spool/tmp") catch |e| switch (e) {
        error.PathAlreadyExists => {},
        else => return e,
    };
    maildir.createDirPath(io, "mailboxes") catch |e| switch (e) {
        error.PathAlreadyExists => {},
        else => return e,
    };
    return .{ .maildir = maildir };
}

pub fn register(self: *Self, io: std.Io, raw: []const u8) !void {
    var buf: [64]u8 = undefined;
    const user = try normalizeUser(raw, &buf);
    if (try self.exists(io, user)) {
        return error.UserExists;
    }
    var mailbox = try self.maildir.openDir(io, "mailboxes", .{});
    defer mailbox.close(io);
    try mailbox.createDir(io, user, @fromBackingInt(@intCast(0o700)));
    var userbox = try mailbox.openDir(io, user, .{});
    defer userbox.close(io);
    try userbox.createDir(io, "tmp", @fromBackingInt(@intCast(0o700)));
    try userbox.createDir(io, "new", @fromBackingInt(@intCast(0o700)));
    try userbox.createDir(io, "cur", @fromBackingInt(@intCast(0o700)));
}

pub fn exists(self: Self, io: std.Io, raw: []const u8) !bool {
    const mailbox = try self.maildir.openDir(io, "mailboxes", .{});
    defer mailbox.close(io);
    _ = mailbox.statFile(io, raw, .{}) catch |e| switch (e) {
        error.FileNotFound => return false,
        else => return e,
    };
    return true;
}