# adapted from https://github.com/samrose/dotfiles-1/blob/8887ca3b01edecd83c2e95f01e42885ce26f76c5/nixos/eve/modules/snappymail.nix#L55
{ pkgs, config, lib, mkDomain, ... }:

let
  maxUploadSize = "256M";
  toKeyValue = lib.generators.toKeyValue {
    mkKeyValue = lib.generators.mkKeyValueDefault {} " = ";
  };

  baseIni = pkgs.runCommand "application.ini" { # eww
  	nativeBuildInputs = [ pkgs.php ];
  } ''
    mkdir /tmp/foobar123
    php-cgi "${pkgs.snappymail.override { dataPath = "/tmp/foobar123"; }}/index.php" >/dev/null
  	cp /tmp/foobar123/_data_/_default_/configs/application.ini $out
  '';

  extendIni = baseFile: fname: args: pkgs.runCommand fname { # eww
    preferLocalBuild = true;
    nativeBuildInputs = [ pkgs.initool ];
  } ''
    cat ${baseFile} |
    ${lib.pipe args [
      (lib.mapAttrsToList (section: data: lib.mapAttrsToList (key: val: { inherit section key val; }) data))
      lib.flatten
      (builtins.map ({ section, key, val }: ''
        initool s - ${lib.escapeShellArgs [ section key val ]} |
      ''))
      lib.concatStrings
    ]}
    cat > $out
  '';

  modifiedIni = with builtins; extendIni baseIni "application.ini" {
    webmail.title = "pbsds SnappyMail";
    webmail.loading_description = "pbsds SnappyMail";
    webmail.messages_per_page = 20;

    contacts.type = "pgsql";
    contacts.pdo_dsn = ''"pgsql:host=/run/postgresql;port=${toString config.services.postgresql.port};dbname=snappymail"'';
    contacts.pdo_user = "snappymail";
    contacts.pdo_password = "";

    login.default_domain = "imap.fyrkat.no";
    #security.allow_admin_panel = "Off";
  };

in
{
  services.phpfpm.pools.snappymail = {
    user  = "snappymail";
    group = "snappymail";
    phpOptions = toKeyValue {
      upload_max_filesize = maxUploadSize;
      post_max_size       = maxUploadSize;
      memory_limit        = maxUploadSize;
    };
    settings = {
      "listen.owner"            = "nginx";
      "listen.group"            = "nginx";
      "pm"                      = "ondemand";
      "pm.max_children"         = 32;
      "pm.process_idle_timeout" = "10s";
      "pm.max_requests"         = 500;
    };
  };

  services.postgresql.ensureDatabases = [ "snappymail" ];
  services.postgresql.ensureUsers = [
    {
      name = "snappymail";
      ensurePermissions."DATABASE snappymail" = "ALL PRIVILEGES";
    }
  ];

  #services.nginx.preStart = ''
  systemd.services."phpfpm-snappymail".preStart = ''
    mkdir -p /var/lib/snappymail/_data_/_default_/configs
    ln -sf ${modifiedIni} /var/lib/snappymail/_data_/_default_/configs/application.ini
  '';

  services.nginx.virtualHosts.${mkDomain "snappymail"} = {
    forceSSL = true; # addSSL = true;
    enableACME = true; #useACMEHost = acmeDomain;
    locations."/".extraConfig = ''
      index index.php;
      autoindex on;
      autoindex_exact_size off;
      autoindex_localtime on;
    '';
    locations."^~ /data".extraConfig = ''
      deny all;
    '';
    locations."~ \.php$".extraConfig = ''
      include ${pkgs.nginx}/conf/fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_pass  unix:${config.services.phpfpm.pools.snappymail.socket};
    '';
    extraConfig = ''
      client_max_body_size ${maxUploadSize};
    '';
    root = pkgs.snappymail.override {
      dataPath = "/var/lib/snappymail"; # the default
    };
  };

  users.users.snappymail = {
    isSystemUser = true;
    createHome   = true;
    home         = "/var/lib/snappymail";
    group        = "snappymail";
  };
  users.groups.snappymail = {};

}
