CREATE TABLE transport (
    domain VARCHAR(128) NOT NULL,
    transport VARCHAR(128) NOT NULL,
    PRIMARY KEY (domain)
);

CREATE TABLE users (
    userid VARCHAR(128) NOT NULL,
    password VARCHAR(128),
    realname VARCHAR(128),
    uid INTEGER NOT NULL,
    gid INTEGER NOT NULL,
    home VARCHAR(128),
    mail VARCHAR(255),
    PRIMARY KEY (userid)
);

CREATE TABLE virtual (
    address VARCHAR(255) NOT NULL,
    userid VARCHAR(255) NOT NULL,
    PRIMARY KEY (address)
);

create view postfix_mailboxes as
select userid, home||'/' as mailbox from users
union all
select domain as userid, 'dummy' as mailbox from transport;

create view postfix_virtual as
select userid, userid as address from users
union all
select userid, address from virtual;

-- TODO: we MUST NOT include default passwords in this script.
-- in future, it would be nice to generate these accounts as part of setup,
-- using credentials provided to us by the user.
-- `mailreader` could be randomly-generated, though.
CREATE USER mailreader PASSWORD 'mailreader-secret';
grant select on transport, users, virtual, postfix_mailboxes, postfix_virtual to mailreader;

create user mailwriter password 'mailwriter-secret';
grant select, insert, update, delete on transport, users, virtual, postfix_mailboxes, postfix_virtual to mailwriter;

-- TODO: remove example users
insert into transport (domain, transport) values ('domain.org', 'virtual:');
insert into transport (domain, transport) values ('foo.org', 'virtual:');
insert into users (userid, uid, gid, home) values ('user@domain.org', 1001, 1001, 'domain.org/mails/user');
insert into users (userid, uid, gid, home) values ('user2@domain.org', 1001, 1001, 'domain.org/mails/user2');
insert into users (userid, uid, gid, home) values ('user@foo.org', 1002, 1002, 'foo.org/mails/user');
insert into virtual (address, userid) values ('foo@foo.org', 'user@foo.org');
