{ lib, config, inputs, hostName, ... }:
let
  inherit (config.networking) domain;
  inherit (config.services) nginx postgresql;
  inherit (config.users) users groups;
  srv = "miniflux";
in
{
  systemd.sockets.miniflux = {
    listenStreams = [ "/run/miniflux.sock" ];
    wantedBy = [ "sockets.target" ];
    socketConfig.SocketMode = "600";
    socketConfig.SocketUser = nginx.user;
  };
  services.miniflux = {
    enable = true;
    config = {
      BASE_URL = "https://${srv}.${domain}"; # Base URL to generate HTML links and base path for cookies.
      BATCH_SIZE = "3"; # Number of feeds to send to the queue for each interval.
      CLEANUP_ARCHIVE_UNREAD_DAYS = "60";
      CLEANUP_ARCHIVE_READ_DAYS = "30";
      #DEBUG = "on";
      LISTEN_ADDR = "";
      #METRICS_COLLECTOR = "1";
      POLLING_FREQUENCY = "180";
      POLLING_SCHEDULER = "entry_frequency";
      SCHEDULER_ENTRY_FREQUENCY_MAX_INTERVAL = "10080"; # 7*24*60 = 7d
      WATCHDOG = "1";
      WORKER_POOL_SIZE = "2";
    };
    adminCredentialsFile = "/run/credentials/miniflux.service/credentials";
  };
  systemd.services.miniflux = {
    partOf = [ "postgresql.service" ];
    # For the socket-activation
    wantedBy = lib.mkForce [ ];
    unitConfig = {
      RefuseManualStart = true;
    };
    serviceConfig = {
      LoadCredentialEncrypted = [
        "credentials:${inputs.self}/hosts/${hostName}/miniflux/credentials.cred"
      ];
      # For postgres auth
      User = users."miniflux".name;
      Group = groups."postgres".name;
      # For the confinement
      BindReadOnlyPaths = [
        "/run/systemd/journal/socket"
        "/run/postgresql"
        "/etc/pki/tls/certs/ca-bundle.crt"
        "/etc/hosts"
      ];
      Type = "notify";
      DynamicUser = lib.mkForce false;
      UMask = lib.mkForce "0022";
      # For the hardening
      NoNewPrivileges = true;
      PrivateTmp = true;
      RemoveIPC = true;
      #ProtectSystem = true;
    };
    confinement = {
      enable = true;
      binSh = null;
      mode = "chroot-only";
    };
  };
  services.postgresql.identMap = ''
    # MAPNAME  SYSTEM-USERNAME         PG-USERNAME
    user       ${users.miniflux.name}  ${users.miniflux.name}
  '';
  users.users."miniflux" = {
    isSystemUser = true;
    group = groups."postgres".name;
  };
  services.nginx.virtualHosts."${srv}.${domain}" = {
    forceSSL = true;
    useACMEHost = domain;
    extraConfig = ''
      access_log /var/log/nginx/${domain}/${srv}/access.log json buffer=32k;
      error_log  /var/log/nginx/${domain}/${srv}/error.log warn;
    '';
    locations."/" = {
      proxyPass = "http://unix:/run/miniflux.sock:/";
    };
  };
  systemd.services.nginx.serviceConfig.LogsDirectory =
    lib.mkForce [ "nginx/${domain}/${srv}" ];
}