{ config, pkgs, ... }:
{

  systemd.network.networks."30-wan".addresses = [
    {
      Address = "2a01:4f8:c012:15d4::/64";
    }
  ];

  services.postgresql = {
    enable = true;
    enableTCPIP = true;
    authentication = pkgs.lib.mkOverride 10 ''
      #type database dbuser origin-address auth-method
      local all all trust
      host all all 100.64.0.0/24 trust # trust tailnet
    '';
    ensureDatabases = [
      "atuin"
      "authelia"
      "forgejo"
      "kinky-vaultwarden"
      "kinky-docuseal"
      "lldap"
      "mealie"
    ];
    ensureUsers = [
      {
        name = "atuin";
        ensureDBOwnership = true;
      }
      {
        name = "authelia";
        ensureDBOwnership = true;
      }
      {
        name = "forgejo";
        ensureDBOwnership = true;
      }
      {
        name = "kinky-vaultwarden";
        ensureDBOwnership = true;
      }
      {
        name = "kinky-docuseal";
        ensureDBOwnership = true;
      }
      {
        name = "lldap";
        ensureDBOwnership = true;
      }
      {
        name = "mealie";
        ensureDBOwnership = true;
      }
    ];
  };

  services.postgresqlBackup = {
    enable = true;
    startAt = "*-*-* 02:00:00";
    databases = [
      "atuin"
      "authelia"
      "forgejo"
      "kinky-vaultwarden"
      "kinky-docuseal"
      "lldap"
      "mealie"
    ];
  };

  services.restic.backups = {
    postgresql = {
      initialize = true;

      repositoryFile = config.sops.secrets.restic-repository.path;
      passwordFile = config.sops.secrets.restic-password.path;
      environmentFile = config.sops.secrets.restic-environment.path;

      timerConfig = {
        OnCalendar = "03:00";
        Persistent = true;
      };

      paths = [
        "/var/backup/postgresql"
      ];

      pruneOpts = [
        "--keep-daily 7"
        "--keep-weekly 5"
        "--keep-weekly 12"
      ];
    };
  };

  sops = {
    defaultSopsFile = ./db-01.yaml;
    validateSopsFiles = false;
    secrets = {
      restic-environment = {
        owner = "root";
      };
      restic-password = {
        owner = "root";
      };
      restic-repository = {
        owner = "root";
      };
    };
  };

  system.stateVersion = "25.05";
}
