# Sources for this configuration:
# - https://nixos.org/manual/nixos/stable/#module-security-acme
# - https://git.grzb.de/yuri/nix-infra/-/blob/33f2d9e324c2e3a8b1b41c20bce239001bcce9fc/hosts/netbox/nginx.nix
# - https://docs.netbox.dev/en/stable/installation/5-http-server/
# - https://github.com/netbox-community/netbox/blob/v3.5.9/contrib/nginx.conf

{ config, pkgs, ... }:

{
  services.nginx = {
    enable = true;
    # So nginx can access the Netbox static files.
    user = "netbox";

    virtualHosts."acme-netbox.hamburg.ccc.de" = {
      default = true;
      enableACME = true;
      serverName = "netbox.hamburg.ccc.de";

      listen = [
        {
          addr = "0.0.0.0";
          port = 31820;
        }
      ];
    };

    virtualHosts."netbox.hamburg.ccc.de" = {
      default = true;
      forceSSL = true;
      useACMEHost = "netbox.hamburg.ccc.de";

      listen = [
        {
          addr = "0.0.0.0";
          port = 8443;
          ssl = true;
          proxyProtocol = true;
        }
      ];

      locations."/static/" = {
        alias = "${config.services.netbox.dataDir}/static/";
      };

      locations."/" = {
        proxyPass = "http://${config.services.netbox.listenAddress}:${builtins.toString config.services.netbox.port}";
      };

      extraConfig = ''
        # Make use of the ngx_http_realip_module to set the $remote_addr and
        # $remote_port to the client address and client port, when using proxy
        # protocol.
        # First set our proxy protocol proxy as trusted.
        set_real_ip_from 172.31.17.140;
        # Then tell the realip_module to get the addreses from the proxy protocol
        # header.
        real_ip_header proxy_protocol;

        client_max_body_size 25m;
      '';
    };
  };

  networking.firewall.allowedTCPPorts = [ 8443 31820 ];
  networking.firewall.allowedUDPPorts = [ 8443 ];
}