]> git.scottworley.com Git - syncthing-autoregister/blobdiff - pkgs/syncthing-set-id.nix
pkg structure
[syncthing-autoregister] / pkgs / syncthing-set-id.nix
diff --git a/pkgs/syncthing-set-id.nix b/pkgs/syncthing-set-id.nix
new file mode 100644 (file)
index 0000000..0277983
--- /dev/null
@@ -0,0 +1,52 @@
+{ coreutils, jq, nix, nixfmt, syncthing, writeShellScriptBin, }:
+writeShellScriptBin "syncthing-set-id" ''
+  set -euo pipefail
+
+  PATH="${coreutils}/bin"
+
+  usage() {
+    cat <<< '
+  usage: syncthing-set-device-id file [name] [id]
+  example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix
+  example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix lappy
+  example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix lappy 1234567-89ABCDE-FGHIJKL-MNOPQRS-TUVWXYZ-0123456-789ABCD-EFGHIJK
+
+  If `name` is not specified, $HOSTNAME is used.
+  If `id` is not specified, the ID of the current system instance is used.
+  ' >&2
+    exit 1
+  }
+
+  [[ $# -lt 1 || "$1" == --help ]] && usage
+  file=$(realpath "$1")
+  name=''${2:-"$HOSTNAME"}
+  if (( $# < 3));then
+    configDir=$(${nix}/bin/nix eval --raw '(import <nixos/nixos> {}).config.services.syncthing.configDir')
+    id=$(${syncthing}/bin/syncthing -home="$configDir" -device-id)
+  else
+    id=$3
+  fi
+
+  if [[ ! -e "$file" ]];then
+    echo "Creating $file" >&2
+    echo '{}' > "$file"
+  fi
+
+  tmp=$(mktemp "$(dirname "$file")/.$(basename "$file").XXXXXXXXXX")
+
+  # Use `nix-instantiate --eval -E --json | jq -r` instead of `nix eval --raw` until
+  # https://github.com/NixOS/nix/issues/2678 is fixed.
+  ${nix}/bin/nix-instantiate --eval -E --json \
+      --argstr file "$file" \
+      --argstr name "$name" \
+      --argstr id   "$id" \
+    '
+      { file, name, id }:
+      let pkgs = import <nixpkgs> { };
+      in pkgs.lib.generators.toPretty { } (pkgs.lib.recursiveUpdate (import file) {
+        services.syncthing.declarative.devices."''${name}".id = id;
+      })
+    ' | ${jq}/bin/jq -r | ${nixfmt}/bin/nixfmt > "$tmp"
+
+  mv "$tmp" "$file"
+''