{ domain, ... }:
{ pkgs, lib, config, hostName, ... }:
let
  inherit (config) networking;
  inherit (config.security) gnupg;
  inherit (config.services) nginx nix-serve;
  inherit (config.users) users groups;
  srv = "nix-serve";
in
{
nix.trustedUsers = [ users."nix-serve".name ];
users.users."nix-serve".extraGroups = [ groups."keys".name ];
security.gnupg.secrets."nix/binary-cache-key/1" = {
  user = users."nix-serve".name;
  systemdConfig = {
    before = [ "nix-serve.service" ];
    wantedBy = [ "nix-serve.service" ];
  };
};
services.nix-serve = {
  enable = true;
  secretKeyFile = gnupg.secrets."nix/binary-cache-key/1".path;
  bindAddress = "127.0.0.1";
};
services.nginx = let vhostConfig = priority:
  {
    #onlySSL = true;
    #addSSL = true;
    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;
      access_log off;
      error_log  /dev/null crit;
    '';
    locations."/nix-cache-info" = {
      # cache.nixos.org has priority 40
      return = ''200 "StoreDir: ${builtins.storeDir}\nWantMassQuery: 1\nPriority: ${toString priority}\n"'';
      extraConfig = ''
        ${nginx.configs.https_add_headers}
        add_header Content-Type text/plain;
      '';
    };
    locations."/".extraConfig = ''
      proxy_pass http://localhost:${toString nix-serve.port};
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    '';
  };
  in {
  virtualHosts."nix-localcache.${domain}" = vhostConfig 30;
  virtualHosts."nix-extracache.${domain}" = vhostConfig 60 // {
    serverAliases = [ "${srv}.${domain}" ];
  };
};
systemd.services.nginx = {
  serviceConfig = {
    LogsDirectory = lib.mkForce ["nginx/${domain}/${srv}"];
  };
};
}