# adapted from github:Misterio77/nix-config
{
  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 = {
      "escapeangle.com" = {
        primary = true;
        address = "lander@escapeangle.com";
        passwordCommand = "cat ${config.sops.secrets.escapeangle-mail-pass.path}";

        imap.host = "mail.escapeangle.com";
        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 = "mail.escapeangle.com";
        userName = "lander@escapeangle.com";
      }
      // common;
    };
  };

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

  systemd.user.services.mbsync = {
    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}
        ''
      );
    };
}
