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

let cfg = config.sydnix.deertopia.servarr.slskd;
in {
	options.sydnix.deertopia.servarr.slskd = {
		enable = lib.mkEnableOption "Slskd (à la Nixarr)";
	};

  config = lib.mkIf cfg.enable {
    sydnix.sops.secrets.slskd-credentials = {
			owner = "torrenter";
		};

	  # TODO: Patch Nixpkgs to add option services.slskd.appDir.

    services.slskd = {
      enable = true;
			user = "torrenter";
			group = "media";

      openFirewall = true;
      domain = null;
      environmentFile = "/run/secrets/slskd-credentials";

      settings = {
        # Disable slskd's authentication in favour of Authelia.
        web.authentication.disabled = true;
        shares.directories = [
          config.nixarr.mediaDir
        ];
				directories = {
				  downloads = "/var/lib/slskd/downloads";
				  incomplete = "/var/lib/slskd/incomplete";
				};
      };
    };

    networking.firewall.allowedTCPPorts = [
      config.services.slskd.settings.web.port
    ];

    sydnix.deertopia.nginx.vhosts."slsk" = {
      directory = null;
      vhost = {
        forceSSL = true;
        enableACME = true;
        extraConfig =
          let port = builtins.toString config.services.slskd.settings.web.port;
          in ''
            include ${../authelia/authelia-location.conf};
            set $upstream http://127.0.0.1:${port};
          '';
        locations."/".extraConfig = ''
          include ${../authelia/authelia-authrequest.conf};
          include ${../authelia/proxy.conf};
          proxy_pass $upstream;
        '';
        locations."/hub".extraConfig = ''
          proxy_pass $upstream;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header X-Forwarded-Protocol $scheme;
          proxy_set_header X-Forwarded-Host $http_host;
        '';
      };
    };
  };
}

