{ pkgs, ... }:

let
  domain = "c3cat.de";
  dataDir = "/var/www/${domain}";
  deployUser = "c3cat-website-deploy";
in {
  security.acme.certs."${domain}".extraDomainNames = [ "www.${domain}" ];

  services.nginx.virtualHosts = {
    "acme-${domain}" = {
      enableACME = true;
      serverName = "${domain}";
      serverAliases = [
        "www.${domain}"
      ];

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

    "$www.${domain}" = {
      forceSSL = true;
      useACMEHost = "${domain}";

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

      locations."/" = {
        return = "302 https://c3cat.de$request_uri";
      };

      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;
      '';
    };

    "${domain}" = {
      forceSSL = true;
      useACMEHost = "${domain}";

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

      root = "${dataDir}";

      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;
      '';
    };
  };

  systemd.tmpfiles.rules = [
    "d ${dataDir} 0755 ${deployUser} ${deployUser}"
  ];

  users.users."${deployUser}" = {
    isNormalUser = true;
    group = "${deployUser}";
    openssh.authorizedKeys.keys = [
      "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIcZJzQO4RYinJm6YDUgCELe8OJA/DYOss+8xp7TtxM0 deploy key for c3cat.de"
    ];
  };
  users.groups."${deployUser}" = { };
}