{ config, pkgs, ... }:
let
  serviceName = "${config.networking.hostName}-paperless";
  domain-name = "${
    config.clan.core.vars.generators."${serviceName}".files.subdomain.value
  }.${config.networking.fqdn}";
in
{
  clan.core.vars.generators."${serviceName}" = {
    files = {
      subdomain.secret = false;
      adminpassword = {
        secret = true;
        owner = config.services.paperless.user;
        group = config.services.paperless.user;
      };
    };
    prompts = {
      subdomain = {
        persist = true;
        type = "line";
        description = "Sub-domain for Paperless. Default:(paperless)";
      };
      adminpassword = {
        persist = true;
        type = "hidden";
        description = "Password for the admin user. Leave empty to auto-generate.";
      };
    };

    runtimeInputs = [
      pkgs.xkcdpass
      pkgs.coreutils
    ];

    script = ''
      prompt_domain=$(cat "$prompts"/subdomain)
      if [[ -n "''${prompt_domain-}" ]]; then
        echo $prompt_domain | tr -d "\n" > "$out"/subdomain
      else
        echo -n "paperless" > "$out"/subdomain
      fi

      prompt_password=$(cat "$prompts"/adminpassword)
      if [[ -n "''${prompt_password-}" ]]; then
        echo "$prompt_password" | tr -d "\n" > "$out"/adminpassword
      else
        xkcdpass --numwords 4 --delimiter - --count 1 | tr -d "\n" > "$out"/adminpassword
      fi
    '';
  };

  environment.systemPackages = [ pkgs.toybox ];

  services.paperless = {
    passwordFile = config.clan.core.vars.generators."${serviceName}".files.adminpassword.path;
  };

  services.nginx.virtualHosts."${domain-name}" = {
    forceSSL = true;
    useACMEHost = "${config.networking.fqdn}";
    locations."/" = {
      proxyPass = "http://localhost:${builtins.toString config.services.paperless.port}";
    };
  };

}
