CREATE TABLE IF NOT EXISTS mail_domains (
    id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    domain text NOT NULL,

    UNIQUE (domain)
);

CREATE TABLE IF NOT EXISTS mail_aliases (
    id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    enabled boolean DEFAULT true NOT NULL,

    alias_username text NOT NULL,
    alias_domain_id integer NOT NULL,

    email_username text NOT NULL,
    email_domain_id integer NOT NULL,

    FOREIGN KEY (alias_domain_id) REFERENCES mail_domains(id) ON DELETE CASCADE,
    FOREIGN KEY (email_domain_id) REFERENCES mail_domains(id) ON DELETE CASCADE,

    UNIQUE (alias_username, alias_domain_id, email_username, email_domain_id)
);

CREATE TABLE IF NOT EXISTS mail_forwards (
    id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    enabled boolean DEFAULT true NOT NULL,
    source text NOT NULL,
    destination text NOT NULL,

    UNIQUE (source, destination)
);

CREATE TABLE IF NOT EXISTS mail_tls (
    id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    enabled boolean DEFAULT true NOT NULL,

    foreign_domain text NOT NULL,

    policy text NOT NULL,
    params text DEFAULT NULL,

    UNIQUE (foreign_domain)
);

CREATE TABLE IF NOT EXISTS mail_users (
    id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    enabled boolean DEFAULT true NOT NULL,

    username text NOT NULL,
    domain_id integer NOT NULL,

    password_plaintext text DEFAULT NULL,
    password_md5 text DEFAULT NULL,
    password_sha1 text DEFAULT NULL,
    password_sha256 text DEFAULT NULL,

    quota_mb integer NOT NULL DEFAULT 0 CHECK (quota_mb >= 0),
    no_reply boolean NOT NULL DEFAULT false,
    allowed_networks text DEFAULT NULL,

    when_created timestamp with time zone DEFAULT now(),

    FOREIGN KEY (domain_id) REFERENCES mail_domains(id) ON DELETE CASCADE,
    UNIQUE (username, domain_id),

    CHECK ((password_md5 IS NOT NULL) OR (password_sha1 IS NOT NULL) OR
           (password_sha256 IS NOT NULL) OR (password_plaintext IS NOT NULL))
);

CREATE TABLE IF NOT EXISTS mail_anyone_shares (
    from_user text NOT NULL,
    dummy character(1) DEFAULT '1'::bpchar,

    UNIQUE (from_user)
);

CREATE TABLE IF NOT EXISTS mail_user_shares (
    from_user text NOT NULL,
    to_user text NOT NULL,
    dummy character(1) DEFAULT '1'::bpchar,

    UNIQUE (from_user, to_user)
);
