{ lib, config, ... }:
with lib;
let
  cfg = config.luj.deluge;
  port = 8112;
in
{

  options.luj.deluge = {
    enable = mkEnableOption "activate deluge service";

    user = mkOption {
      type = types.str;
      default = "deluge";
      description = "User account under which deluge runs.";
    };

    group = mkOption {
      type = types.str;
      default = "deluge";
      description = "Group under which deluge runs.";
    };

    nginx.enable = mkEnableOption "activate nginx";
    nginx.subdomain = mkOption { type = types.str; };
  };

  config = mkIf cfg.enable (mkMerge [
    {

      age.secrets.deluge-webui-password = {
        owner = cfg.user;
        file = ../../secrets/deluge-webui-password.age;
      };

      services.deluge = {
        enable = true;
        inherit (cfg) user group;
        openFirewall = true;
        declarative = true;
        authFile = "/run/agenix/deluge-webui-password";
        web.enable = true;
        config = {
          download_location = "/home/mediaserver/downloads/complete/";
          allow_remote = true;
        };
        dataDir = "/home/mediaserver/deluge";
      };
    }

    (mkIf cfg.nginx.enable (mkVPNSubdomain cfg.nginx.subdomain port))
  ]);
}
