]> git.scottworley.com Git - syncthing-autoregister/blame - pkgs/syncthing-set-id.nix
Follow services.syncthing.declarative rename
[syncthing-autoregister] / pkgs / syncthing-set-id.nix
CommitLineData
0c29f01e
SW
1{ coreutils, jq, nix, nixfmt, syncthing, writeShellScriptBin, }:
2writeShellScriptBin "syncthing-set-id" ''
3 set -euo pipefail
4
5 PATH="${coreutils}/bin"
6
7 usage() {
8 cat <<< '
9 usage: syncthing-set-device-id file [name] [id]
10 example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix
11 example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix lappy
12 example: syncthing-set-device-id /etc/nixos/modules/syncthing-devices.nix lappy 1234567-89ABCDE-FGHIJKL-MNOPQRS-TUVWXYZ-0123456-789ABCD-EFGHIJK
13
14 If `name` is not specified, $HOSTNAME is used.
15 If `id` is not specified, the ID of the current system instance is used.
16 ' >&2
17 exit 1
18 }
19
20 [[ $# -lt 1 || "$1" == --help ]] && usage
21 file=$(realpath "$1")
22 name=''${2:-"$HOSTNAME"}
23 if (( $# < 3));then
274332f7 24 configDir=$(${nix}/bin/nix --experimental-features nix-command eval --impure --raw --expr '(import <nixos/nixos> {}).config.services.syncthing.configDir')
0c29f01e
SW
25 id=$(${syncthing}/bin/syncthing -home="$configDir" -device-id)
26 else
27 id=$3
28 fi
29
30 if [[ ! -e "$file" ]];then
31 echo "Creating $file" >&2
32 echo '{}' > "$file"
33 fi
34
35 tmp=$(mktemp "$(dirname "$file")/.$(basename "$file").XXXXXXXXXX")
36
37 # Use `nix-instantiate --eval -E --json | jq -r` instead of `nix eval --raw` until
38 # https://github.com/NixOS/nix/issues/2678 is fixed.
39 ${nix}/bin/nix-instantiate --eval -E --json \
40 --argstr file "$file" \
41 --argstr name "$name" \
42 --argstr id "$id" \
43 '
44 { file, name, id }:
45 let pkgs = import <nixpkgs> { };
46 in pkgs.lib.generators.toPretty { } (pkgs.lib.recursiveUpdate (import file) {
22596d75 47 services.syncthing.devices."''${name}".id = id;
0c29f01e
SW
48 })
49 ' | ${jq}/bin/jq -r | ${nixfmt}/bin/nixfmt > "$tmp"
50
51 mv "$tmp" "$file"
52''