{ lib
, config
, pkgs
, ...
}:

with lib;
let
  cfg = config.my.profiles.personal;

  filterHtml = pkgs.writeScript "filter_html" ''
    ${lib.getExe pkgs.w3m} -T text/html \
        -cols $(tput cols) \
        -dump \
        -o display_image=false \
        -o display_link_number=true "$@"
  '';
in
{
  options.my.profiles.personal.mail = mkEnableOption "personal email";

  config = mkIf cfg.mail {
    home-manager.users.moritz = {
      home.packages = with pkgs; [
        w3m
      ];
      programs.aerc = {
        enable = true;
        extraConfig = {
          general.unsafe-accounts-conf = true;
          viewer = {
            alternatives = "text/plain,text/html";
            header-layout = "From,To,Cc,Bcc,Date,Subject";
          };
          filters = {
            "text/html" = "${filterHtml}";
            "text/plain" = "colorize";
            "text/calendar" = "calendar";
            "message/delivery-status" = "colorize";
            "message/rfc822" = "colorize";
            ".headers" = "colorize";
          };
        };
      };
      services.mbsync.enable = true;
      services.imapnotify.enable = true;
      programs.mbsync.enable = true;
      accounts.email.accounts.personal = {
        imapnotify.enable = true;
        imapnotify.boxes = [ "Inbox" ];
        imapnotify.onNotify = "${lib.getExe' pkgs.systemd "systemctl"} start --user mbsync.service";
        primary = true;
        address = "mail@moritzboeh.me";
        userName = "mail@moritzboeh.me";
        aerc.enable = true;
        gpg.signByDefault = true;
        gpg.key = "0xE4F362A3F5C338A0";
        imap.host = "mail.your-server.de";
        smtp.host = "mail.your-server.de";
        realName = "Moritz Böhme";
        mbsync.enable = true;
        mbsync.create = "both";
        mbsync.remove = "both";
        mbsync.expunge = "both";
        passwordCommand = "${lib.getExe' pkgs.coreutils "cat"} /run/agenix/email";
      };
      accounts.email.maildirBasePath = "Documents/Mail";
    };
    age.secrets.email = {
      file = ../../secrets/email.age;
      owner = "1000";
    };
  };
}
