{ flake, config, ... }:
let
  inherit (flake.config.machines.devices)
    phone
    mars
    ceres
    ;
  inherit (flake.config.services)
    instances
    ;
  service = instances.syncthing;

  hostname = config.networking.hostName;
  localhost = instances.web.localhost.address1;
  postgres = instances.postgresql;
  forgejo = instances.forgejo;
  vaultwarden = instances.vaultwarden;
  backupPath = "${service.paths.path1}";

  syncDevices = {
    phoneSync = {
      ${phone.name} = {
        autoAcceptFolders = true;
        name = phone.name;
        addresses = [
          "tcp://${phone.ip.address0}:${toString service.ports.port2}"
        ];
        id = phone.sync.address0;
      };
    };
  };
in
{
  services = {
    syncthing = {
      enable = true;
      overrideDevices = false;
      overrideFolders = false;
      openDefaultPorts = true;
      systemService = true;
      guiAddress = "${localhost}:${toString service.ports.port0}";
      settings = {
        devices = if hostname == mars.name then syncDevices.phoneSync else { };
      };
    };
  };

  systemd.tmpfiles.rules = [
    # Main syncthing directory - use Z to fix existing permissions
    "z ${service.paths.path0} 0755 ${service.name} ${service.name} -"
    # Backup directories
    "d ${backupPath} 0755 ${service.name} ${service.name} -"
    "d ${backupPath}/${postgres.name} 0750 ${postgres.name} ${service.name} -"
    "d ${backupPath}/${forgejo.name} 0750 ${forgejo.name} ${service.name} -"
    "d ${backupPath}/${vaultwarden.name} 0750 ${vaultwarden.name} ${service.name} -"
  ];

  networking = {
    firewall = {
      allowedTCPPorts = [
        service.ports.port0
        service.ports.port1
        service.ports.port2
      ];
    };
  };
}
