{ config, pkgs, mod, ... }:

let
  home = "/var/lib/nix-serve";
  domain = "cache.${config.networking.privateDomain}";
in {
  services.nginx.virtualHosts.${domain} = {
    listenPrivate = true;

    locations = {
      "/".proxyPass = "http://127.0.0.1:${toString config.services.nix-serve.port}";
      "/nix-cache-info".root = pkgs.writeTextDir "nix-cache-info" ''
        StoreDir: /nix/store
        WantMassQuery: 1
        Priority: 10
      '';
    };
  };

  services.nix-serve = {
    enable = true;
    secretKeyFile = "${home}/nix-cache-key.sec";
  };

  users.users.nix-serve = {
    inherit home;
    createHome = true;
  };

  systemd.services.nix-serve.preStart = ''
    if [ ! -f ${home}/nix-cache-key.sec ]; then
      nix-store \
        --generate-binary-cache-key \
        ${config.networking.hostName}-cache \
        ${home}/nix-cache-key.sec \
        ${home}/nix-cache-key.pub

      chown nix-serve ${home}/nix-cache-key.*
    fi
  '';
}