# adapted from github:Misterio77/nix-config
{
  pkgs,
  lib,
  config,
  ...
}: let
  mbsync = "$(config.programs.mbsync.package}/bin/mbsync";

  common = rec {
    realName = "Lander Van den Bulcke";
    gpg = {
      key = "4BE1 2570 1558 0BAB 9F4B 9D5F CA5B 1C34 E649 BF92";
      signByDefault = true;
    };
    signature = {
      showSignature = "append";
      text = ''
        ${realName}

        PGP: ${gpg.key}
      '';
    };
  };
in {
  accounts.email = {
    maildirBasePath = "Mail";
    accounts = {
      inuits =
        rec {
          primary = true;
          address = "landervdb@inuits.eu";
          passwordCommand = "cat ${config.sops.secrets.inuits-mail-pass.path}";

          imap.host = "zimbra88.inuits.eu";
          mbsync = {
            enable = true;
            create = "maildir";
            expunge = "both";
          };
          folders = {
            inbox = "Inbox";
            drafts = "Drafts";
            sent = "Sent";
            trash = "Trash";
          };
          neomutt = {
            enable = true;
            extraMailboxes = [
              "Archive"
              "Drafts"
              "Junk"
              "Sent"
              "Trash"
            ];
          };

          msmtp.enable = true;
          smtp.host = "zimbra88.inuits.eu";
          userName = "landervdb";
        }
        // common;
    };
  };

  programs.mbsync.enable = true;
  programs.msmtp.enable = true;

  systemd.user.services.mbsynce = {
    Unit = {
      Description = "mbsync synchronization";
    };
    Service = {
      Type = "oneshot";
      ExecStart = "${mbsync} -a";
    };
  };
  systemd.user.timers.mbsync = {
    Unit = {
      Description = "Automatic mbsync synchronization";
    };
    Timer = {
      OnBootSec = "30";
      OnUnitActiveSec = "5m";
    };
    Install = {
      WantedBy = ["timers.target"];
    };
  };

  # run `createMaildir`  after `linkGeneration`
  home.activation = let
    mbsyncAccounts = lib.filter (a: a.mbsync.enable) (lib.attrValues config.accounts.email.accounts);
  in
    lib.mkIf (mbsyncAccounts != []) {
      createMaildir = lib.mkForce (lib.hm.dag.entryAfter ["linkGeneration"] ''
        run mkdir -m700 -p $VERBOSE_ARG ${
          lib.concatMapStringsSep " " (a: a.maildir.absPath) mbsyncAccounts
        }
      '');
    };
}
