{
  self,
  tree,
  lib,
  inputs,
  config,
  pkgs,
  hostPath,
  ...
}: let
  inherit (lib.modules) mkMerge;
  inherit (lib.lists) forEach;

  ports = [
    # SMTP
    25
    # Submission
    587
    # Submission w/ SSL
    465
    # IMAP
    143
    # IMAP w/ SSL
    993
    # Sieve
    4190
  ];

  containerLib = import "${self}/lib/containerLib.nix" {
    inherit lib;
  };

  # Using secrets from Host
  secrets = config.services.secrets.secrets;
  secretsList = [
    "mail_restic_password"
    "mail_restic_env"
    "private_mail_aliases"
    "chaos_mail_passwd"
    "system_mail_passwd"
    "gotosocial_mail_passwd"
  ];
  sharedFiles = [
    "/var/lib/acme/mail.owo.monster/fullchain.pem"
    "/var/lib/acme/mail.owo.monster/key.pem"
  ];
in {
  containers.mail = {
    autoStart = true;

    bindMounts = mkMerge [
      (containerLib.genBindHostsForSecrets secrets secretsList)

      (mkMerge (forEach sharedFiles (file: {
        "${file}" = {
          hostPath = "${file}";
        };
      })))
    ];

    specialArgs = {
      inherit inputs;
      inherit tree;
      inherit self;
      inherit hostPath;
      hostSecrets = secrets;
    };

    config = {config, ...}: {
      nixpkgs.pkgs = pkgs;

      imports = with tree;
        [
          profiles.base
          inputs.home-manager-unstable.nixosModules.home-manager

          profiles.nginx
          modules.nixos.secrets

          users.root
        ]
        ++ (with hosts.hetzner-vm.containers.mail; [
          modules.mailserver
          profiles.mailserver
          profiles.restic
        ]);

      # For Shared Secrets
      systemd.tmpfiles.rules = [
        "d ${config.services.secrets.secretsDir} - root root"
        "d /var/lib/acme - root root"
        "d /var/lib/acme/mail.owo.monster - root root"
      ];

      networking.firewall = {
        enable = false;
      };

      home-manager.users.root = {
        imports = with tree; [home.base home.dev.small];

        home.stateVersion = "23.05";
      };

      # Manually configure nameserver. Using resolved inside the container seems to fail
      # currently
      environment.etc."resolv.conf".text = "nameserver 8.8.8.8";
      system.stateVersion = "23.05";
    };
  };

  # users for secrets
  users.users."dovecot2" = {
    uid = config.ids.uids.dovecot2;
    group = "dovecot2";
  };
  users.groups."dovecot2".gid = config.ids.gids.dovecot2;

  # ssl for mail
  services.nginx = {
    enable = true;
    virtualHosts."mail.owo.monster" = {
      serverName = "mail.owo.monster";
      serverAliases = ["owo.monster"];
      forceSSL = true;
      enableACME = true;
      acmeRoot = "/var/lib/acme/acme-challenge";
      # also being used for webmail
      locations."/" = {
        proxyPass = "http://unix:/var/lib/nixos-containers/mail/var/sockets/roundcube.sock";
      };
    };
  };

  networking.firewall = {
    allowedTCPPorts = ports;
    allowedUDPPorts = ports;
  };
}