{ config, lib, pkgs, ...}:

# todo: portable service and system-manager

{

  environment.systemPackages = lib.mkIf config.services.syncthing.enable [
    (pkgs.makeDesktopItem {
      desktopName = "Open Syncthing";
      name = "Syncthing";
      exec = "${pkgs.xdg-utils}/bin/xdg-open http://${config.services.syncthing.guiAddress}";
      icon = "${pkgs.syncthing.src}/assets/logo-512.png";
    })
  ];

  services.syncthing = {
    enable = true;

    user = lib.mkDefault "pbsds";
    group = lib.mkDefault "pbsds";
    dataDir = lib.mkDefault (config.users.users.pbsds.home + "/syncthing");

    overrideDevices = true; # overrides devices from WebUI
    overrideFolders = true; # overrides folders from WebUI

    settings = {
      options.urAccepted = -1; # disable telemetry

      # TODO: nox
      # TODO: eple
      # TODO: somehow disable gui
      # TODO: somehow auto-make a gui user+password
      # TODO: somehow don't create ~/Sync
      # TODO: sync documents folder
      # TODO: move state folder

      # webui http://localhost:8384/
      # nix run -- nixpkgs#syncthing generate --config="$HOME"/syncthing/.config/syncthing
      devices."bjarte".id    = "C7QQYJU-PMJDP2Z-CKTAV4A-V6IFEG5-YFBGCNU-PJPCZFC-QSXKZY3-NC5WRAL";
      devices."pjudduzen".id = "JCNX5AC-YMXJZBP-5LQRLAL-BGTSXKK-X6AJPXL-IXDWJGW-IHSBTPT-AFXKFAK";
      devices."rocm".id      = "UFW6V4E-LMEDTYR-23BU6BP-2HEMWYB-2ARCJ4X-T67WHZX-BNCCHZ4-5GPSZQV";
      devices."sopp".id      = "ZQJEWAX-GALDJDO-FBOE5ON-M5XKXNT-PRZD3CY-S7L3XDR-PR27NYL-RZ6O7QW";
      devices."nord".id      = "C6N5NVA-AXCQ23G-4D4U3A6-WLNXCRC-PBE3PLB-P4SATUU-PSB2MN2-WOZPHAL";
      /* devices."bjarte".autoAcceptFolders = true; # TODO */

      folders = lib.flip lib.pipe [
        # add `path` default
        (lib.mapAttrs (name: attrs: { path = lib.mkDefault "${config.services.syncthing.dataDir}/${name}"; } // attrs ))
        # filter folders this host does not have access to
        (lib.mapAttrsToList (name: attrs: lib.mkIf (builtins.elem config.networking.hostName (attrs.devices or [])) { ${name} = attrs; } ))
        lib.mkMerge
      ] {
        /* "ntnu".ignorePerms = false; # `false` means sync file permissions */
        "DCIM".devices               = [ "pjudduzen" "bjarte" "sopp" ];
        "ntnu".devices               = [ "bjarte" "sopp" "rocm" ];
        "mihon".devices              = [ "pjudduzen" "bjarte" "nord" ];
        "ewesticker".devices         = [ "pjudduzen" "bjarte" "sopp" "rocm" "nord" ];
        "pjudduzen-clover".devices   = [ "pjudduzen" "sopp" ];
        "pjudduzen-movies".devices   = [ "pjudduzen" "sopp" ];
        "pjudduzen-music".devices    = [ "pjudduzen" "sopp" ];
        "pjudduzen-pictures".devices = [ "pjudduzen" "sopp" "bjarte" ];
        "pjudduzen-snapchat".devices = [ "pjudduzen" "sopp" ];
        /* "foobar".type = "receiveencrypted"; */
      };

    };
  };
}
