{ config, lib, pkgs, ... }:

with lib;

let cfg = config.sydnix.deertopia.webdav;
in {
  options = {
    sydnix.deertopia.webdav = {
      enable = mkEnableOption "Deertopia's WebDAV server";

      port = lib.mkOption {
        default = 22016;
        type = lib.types.port;
        description = ''
          The internal WebDAV port.  The actual server will be hosted at
          https://dav.deertopia.net:80/.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    systemd.services.deertopia-webdav-server =
      let htpasswdFile = "/persist/deertopia.net/htpasswd";
          directory = "/persist/deertopia.net/dav";
      in {
        description = "Deertopia's WebDAV server";
        after = [ "network.target" ];
        wantedBy = [ "multi-user.target" ];
        # TODO: Exclude .git.
        # TODO: Respect .gitignore.
        script = ''
          ${pkgs.rclone}/bin/rclone serve webdav \
            --addr ":${builtins.toString cfg.port}" \
            --htpasswd "${htpasswdFile}" "${directory}"
        '';
        serviceConfig.Restart = "always";
      };

    # Without this, Nginx will attempt redirections to https://localhost, which
    # is not okay, as localhost does not have any associated certs!
    # See: https://forum.seafile.com/t/seafdav-move-command-causing-502/11582/26
    services.nginx.appendHttpConfig = ''
      map $http_destination $http_destination_webdav {
        ~*https://(.+) http://$1;
        default $http_destination;
      }
    '';

    sydnix.deertopia.nginx.vhosts."dav".vhost = {
      forceSSL = true;
      enableACME = true;
      locations."/" = {
        extraConfig = ''
          proxy_set_header Host $host;
          proxy_set_header X-Forwarded-For $remote_addr;
          # See previous note regarding the HTTPS -> HTTP redirection.
          proxy_set_header Destination $http_destination_webdav;

          proxy_pass "http://localhost:${builtins.toString cfg.port}";
        '';
      };
    };
  };
}
