{
  config,
  pkgs,
  lib,
  ...
}:
let
  backupDir = "/var/backups/invoiceplane";
in
{
  imports = [
    ./override.nix
  ];

  options.momo-cloud.invoiceplane = with lib; {
    enable = mkEnableOption "Enable invoiceplane instance";
    passwordFile = mkOption {
      type = types.nullOr types.path;
      default = null;
    };
  };

  config = lib.mkIf config.momo-cloud.invoiceplane.enable {
    momo-cloud.nginx.enable = true;
    momo-cloud.acme.enable = true;
    momo-cloud.postgresql.enable = true;

    security.acme.certs = {
      "invoicing.${config.momo-cloud.networking.domain}" = { };
    };

    services.nginx.virtualHosts = {
      "invoicing.${config.momo-cloud.networking.domain}" = {
        forceSSL = true;
        useACMEHost = "invoicing.${config.momo-cloud.networking.domain}";
        listenAddresses = [
          config.momo-cloud.wireguard.ipv4.address
          "[${config.momo-cloud.wireguard.ipv6.address}]"
        ];
      };
    };

    services.invoiceplane.webserver = "nginx";
    services.invoiceplane.sites."invoicing.${config.momo-cloud.networking.domain}" = {
      enable = true;

      database = {
        user = "invoiceplane";
        name = "invoiceplane";
        host = "127.0.0.1";
        port = 3306;
        createLocally = true;
        passwordFile = config.momo-cloud.invoiceplane.passwordFile;
      };

      invoiceTemplates = [ pkgs.invoiceplane-template ];

      settings = {
        SETUP_COMPLETED = true;
        DISABLE_SETUP = true;
        IP_URL = "https://invoicing.${config.momo-cloud.networking.domain}";
      };

      poolConfig = {
        "pm" = "dynamic";
        "pm.max_children" = 32;
        "pm.max_requests" = 500;
        "pm.max_spare_servers" = 4;
        "pm.min_spare_servers" = 2;
        "pm.start_servers" = 2;
        "php_admin_value[error_log]" =
          "/var/lib/invoiceplane/invoicing.${config.momo-cloud.networking.domain}/logs/php-error.log";
        "php_admin_flag[display_errors]" = "off";
        "php_admin_flag[log_errors]" = "on";
        "catch_workers_output" = "yes";
      };
    };

    systemd.tmpfiles.rules = [
      "d '${backupDir}' 0700 root root - -"
    ];

    momo-cloud.backups.restic.invoiceplane = {
      paths = [
        backupDir
        "/var/lib/invoiceplane/invoicing.${config.momo-cloud.networking.domain}"
      ];
      initialize = true;
      backupPrepareCommand = ''
        ${pkgs.sudo}/bin/sudo -u invoiceplane ${config.services.mysql.package}/bin/mariadb-dump --databases invoiceplane > "${backupDir}/invoiceplane.sql"
      '';
      backupCleanupCommand = ''
        rm -rf ${backupDir}/*
      '';
    };
  };
}