{
  flake,
  lib,
  pkgs,
  ...
}:
let
  inherit (flake.config.machines.devices) ceres;
  inherit (flake.config.services) instances;

  service = instances.postgresql;
  # backupPath = "${instances.syncthing.paths.path1}/${service.name}";
in
{
  services = {
    postgresqlBackup = {
      enable = true;
      # location = backupPath;
      # compression = "zstd";
      startAt = "*-*-* 07:00:00";
      databases = [
        instances.mastodon.name
        instances.firefly-iii.name
      ];
    };
    postgresql = {
      enable = true;
    };
  };
  networking = {
    firewall = {
      allowedTCPPorts = [
        service.ports.port0
      ];
    };
  };

  fileSystems."/var/lib/postgresql" = {
    device = service.paths.path0;
    fsType = "none";
    options = [
      "bind"
    ];
    depends = [
      ceres.storage0.mount
    ];
  };

  users.users.${service.name}.extraGroups = [
    instances.mastodon.name
    instances.forgejo.name
    instances.syncthing.name
  ];

  systemd.services.sync-postgres-backups = {
    description = "Sync PostgreSQL backups to Syncthing";
    after = [
      "postgresqlBackup-firefly-iii.service"
      "postgresqlBackup-mastodon.service"
    ];
    serviceConfig = {
      Type = "oneshot";
      User = instances.syncthing.name;
      Group = instances.syncthing.name;
    };
    script = ''
      ${pkgs.rsync}/bin/rsync -av --delete \
        /var/backup/postgresql/ \
        ${instances.syncthing.paths.path1}/${service.name}/

      ${pkgs.rsync}/bin/rsync -av --delete \
        /var/lib/${instances.firefly-iii.name}/storage/ \
        ${instances.syncthing.paths.path1}/${service.name}/firefly-iii-storage/
    '';
  };

  systemd.timers.sync-postgres-backups = {
    wantedBy = [ "timers.target" ];
    timerConfig = {
      OnCalendar = "*-*-* 22:10:00"; # 10 mins after backup
      Persistent = true;
    };
  };
}
