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

let cfg = config.sydnix.deertopia.slskd;
in {
  options = {
    sydnix.deertopia.slskd = {
      enable = lib.mkEnableOption "Soulseek";
    };
  };

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

    services.slskd = {
      enable = true;

      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}/library"
        ];
        soulseek.description = ''
          hi }:).  i share my entire media directory, with a good
          amount of non-music stuff.  this account is for a slskd
          instance i leave running 24/7.

          a while back, i reconfigured both my network setup and my
          share directories, forgetting to update them in soulseek.
          thus, i've been unknowingly leeching for several months.  i
          only noticed once i realise someone banned me from
          downloading, and looking up why one would do that LOL.  i'm
          very sorry for that.
        '';
        soulseek.picture = ./slskd/deer.png;
      };
    };

    # HACK: Consult with Molly on idiomatic Unix permissions.
    users.users.${config.services.slskd.user}.extraGroups = [ "media" ];

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