{ pkgs, ...}@all: with all;
{
  sops.secrets = {
    "nx2site/sslCertificate.pem" = { owner = config.services.nginx.user; };
    "nx2site/sslCertificateKey.pem" = { owner = config.services.nginx.user; };
    "nx2site/dhparams.pem" = { owner = config.services.nginx.user; };
  };
  security.acme = {
    acceptTerms = true;
    defaults = {
      email = "acme@${hyper.domain}";
      webroot = config.services.nginx.virtualHosts."${hyper.domain}".root;
      group = "nginx";
    };
    certs = {
      "${hyper.domain}" = {
        extraDomainNames = builtins.map (subd: "${subd}.${hyper.domain}") [ "sync" ];
      };
    };
  };
  users.users."nginx" = {
    extraGroups = [ "nginx" "acme" "copyparty" ];
    useDefaultShell = false;
    linger = true;
    home = "/var/nginx/";
    homeMode = "770";
    createHome = true;
    isSystemUser = true;
    isNormalUser = false;
  };
  systemd.services.nginx.serviceConfig.ProtectHome = "read-only";
	services.nginx = let 
    dl = [ 
      { addr = "0.0.0.0"; port = 443; ssl = true; }
      { addr = "0.0.0.0"; port = 80; ssl = false; }
      { addr = "[::0]"; port = 443; ssl = true; }
      { addr = "[::0]"; port = 80; ssl = false; }
    ];
  in {
    enable = true;
    user = "nginx";
    group = "nginx";
    additionalModules = [];
    # appendConfig = '''';
    clientMaxBodySize = "20m";
    defaultHTTPListenPort = 80;
    defaultListenAddresses = [ "0.0.0.0" ] ++ lib.optional config.networking.enableIPv6 "[::0]";
    defaultListen = dl;
    defaultMimeTypes = "${pkgs.mailcap}/etc/nginx/mime.types";
    defaultSSLListenPort = 443;
    enableQuicBPF = true;
    enableReload = true;
    package = pkgs.nginxQuic;
    proxyResolveWhileRunning = false;
    proxyTimeout = "20s";
    recommendedBrotliSettings = true;
    recommendedGzipSettings = true;
    recommendedOptimisation = true;
    recommendedProxySettings = true;
    recommendedTlsSettings = true;
    recommendedZstdSettings = true;
    serverTokens = false;
    sslDhparam = config.sops.secrets."nx2site/dhparams.pem".path;
    sslProtocols = "TLSv1.2 TLSv1.3";
    statusPage = false;
    streamConfig = ""; # udp config
    validateConfigFile = true;
    upstreams = {
      "partysock" = {
        servers."unix:/dev/shm/party.sock".fail_timeout = "1s";
        extraConfig = /* nginx */ ''
          keepalive 1;
        '';
      };
    };
    virtualHosts = let
      vh = {
        kTLS = true;
        http2 = true;
        http3 = true;
        http3_hq = true;
        quic = true;
        forceSSL = true;
        enableACME = true;
      };
    in {
      "${hyper.domain}" = vh // {
        # root = "/var/nginx/webroot";
        root = "/var/lib/hugo/nx2site/public";
        default = true;
        listen = dl;
        locations = {
          "/".extraConfig = ''
            index index.html;
          '';
          "~ ^(/.well-known/matrix/client)$".return = "502";
          "~ ^(/.well-known/matrix/server)$".return = "502";
          "~ ^(/phone)$".return                     = "301 /cards/phone";
          "~ ^(/about-me)$".return                  = "301 /slides/about-me";
          "~ ^(/about-this-site)$".return           = "301 /slides/about-this-site";
          "~ ^(/gpg)$".return                       = "301 /cards/gpg";
          "~ ^(/contact)$".return                   = "301 /cards/contact";
          "~ ^(/ba)$".return                        = "301 /BA.pdf";
        }; 
      }; 
      "matrix.${hyper.domain}" = {
        listen = dl;
        locations."~.*".return = "502";
      };
      # "pw.${hyper.domain}" = vh // {
      #   listen = dl;
      #   locations = let d = "pw.docker:80"; in {
      #     "/" = { proxyPass = "http://${d}"; };
      #     "/admin" = { proxyPass = "http://${d}"; };
      #     "/notifications/hub" = { proxyPass = "http://${d}"; };
      #     "/notifications/hub/negotiate" = { proxyPass = "http://${d}"; };
      #   }; 
      # };
      "pw.${hyper.domain}" = vh // {
        listen = dl;
        locations = let 
          d = with config.services.vaultwarden.config; "${ROCKET_ADDRESS}:${builtins.toString ROCKET_PORT}"; 
        in {
          "/" = { proxyPass = "http://${d}"; };
          "/admin" = { proxyPass = "http://${d}"; };
          "/notifications/hub" = { proxyPass = "http://${d}"; };
          "/notifications/hub/negotiate" = { proxyPass = "http://${d}"; };
        }; 
      };
      "sync.${hyper.domain}" = vh // {
        listen = dl;
        locations = { "/" = { proxyPass = "http://127.0.0.1:8384"; }; }; 
      };
      # "git.${hyper.domain}" = vh // {
      #   listen = dl;
      #   locations = { "/" = { proxyPass = "http://git.docker:3000"; }; }; 
      # };
      "git.${hyper.domain}" = vh // {
        http2 = false;
        listen = dl;
        locations = {
          "/" = { proxyPass = "http://127.0.0.1:3000"; };
          "/robots.txt" = {
            extraConfig = ''
              default_type text/plain;
              return 200 "User-agent: *\nDisallow: /\nAllow: /explore/repos\nAllow: /nx2/dotdiles\nAllow: /nx2";
            '';
          };
        }; 
      };
      "doc.${hyper.domain}" = vh // {
        listen = dl;
        locations = { "/" = { proxyPass = "http://127.0.0.1:8441"; }; }; 
      };
      "dav.${hyper.domain}" = lib.mkIf config.services.radicale.enable (vh // {
        listen = dl;
        locations = { "/" = { proxyPass = "http://127.0.0.1:5232"; }; }; 
      });
      # "nc.${hyper.domain}" = vh // {
      #   # directly to nc 
      # };
      "abs.${hyper.domain}" = vh // {
        listen = dl;
        locations."/" = { 
          proxyPass = "http://127.0.0.1:${builtins.toString config.services.audiobookshelf.port}";
          proxyWebsockets = true;
        }; 
      };
      "pnx.${hyper.domain}" = vh // {
        listen = dl;
        locations."/" = { 
          proxyPass = "http://127.0.0.1:8040";
          proxyWebsockets = true;
        }; 
      };
      "old.${hyper.domain}" = vh // {
        listen = dl; 
        root = "/var/nginx/webroot";
      };
      "dev.${hyper.domain}" = vh // {
        listen = dl;
        locations."/" = { 
          proxyPass = "http://127.0.0.1:8080";
          proxyWebsockets = true;
        }; 
      };
      # is done atomatically
      # "cal.${hyper.domain}" = vh // {
      #   listen = dl;
      #   locations = { "/" = { 
      #     proxyPass = "http://unix:///run/open-web-calendar/socket";
      #     proxyWebsockets = true;
      #   }; }; 
      # };
      "file.${hyper.domain}" = { # copyparty
        listen = dl;
        forceSSL = true;
        enableACME = true;
        locations = {
          "/" = {
            proxyPass = "http://partysock";
            proxyWebsockets = true;
            extraConfig = /* nginx */ ''
          		proxy_redirect off;
          		# disable buffering (next 4 lines)
          		# proxy_http_version 1.1; # this is set by nixos
          		client_max_body_size 0;
          		proxy_buffering off;
          		proxy_request_buffering off;
          		# improve download speed from 600 to 1500 MiB/s
          		proxy_buffers 32 8k;
          		proxy_buffer_size 16k;
          		proxy_busy_buffers_size 24k;

          		proxy_set_header   Connection        "Keep-Alive";
          		proxy_set_header   Host              $host;
          		proxy_set_header   X-Real-IP         $remote_addr;
          		proxy_set_header   X-Forwarded-Proto $scheme;
          		proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
          		# NOTE: with cloudflare you want this X-Forwarded-For instead:
          		#proxy_set_header   X-Forwarded-For   $http_cf_connecting_ip;
            ''; 
          };
        };
      };
      "~^(.*).${hyper.domain}$" = {
        listen = dl;
        root = "/var/nginx/webroot";
        locations."~.*".return = "502";
      };
    };
  };
}

