about summary refs log tree commit diff stats
path: root/hm/soispha/conf/unison/default.nix
blob: ec34d038f3060fa175132b977df51f8d189c6c65 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
{
  lib,
  config,
  nixosConfig,
  sysLib,
  pkgs,
  ...
}: let
  unisonPath = "${config.xdg.dataHome}/unison";

  # These are only used for the script
  unisonOptions = {
    sshcmd = "ssh";
    ui = "text";
    auto = "true";
  };

  paths_to_keep = [
    "~/.local/state/mpv"
    "~/.local/state/nvim"
    "~/.local/share"
    "~/.local/.Trash-1000"

    "~/.mozilla/.Trash-1000"
    "~/.mozilla/firefox"

    "~/media"
    "~/school"
    "~/repos"
  ];

  hostName = let
    hn = nixosConfig.networking.hostName;
  in
    if hn == "tiamat"
    then "apzu"
    else if hn == "apzu"
    then "tiamat"
    else builtins.throw "Host (${hn}) not yet covered in the unison host mapping.";

  mkPath = path:
    if lib.strings.hasPrefix "~" path
    then "${builtins.elemAt (builtins.attrNames config.home.persistence)
      0}${lib.strings.removePrefix "~" path}"
    else
      builtins.throw
      "Every pathname needs to start with a '~'";

  mkPair = pathname: let
    path = mkPath pathname;
  in {
    name = "${pathname}";
    value = {
      stateDirectory = unisonPath;
      roots = [
        "${path}"
        "ssh://${config.home.username}@${hostName}.fritz.box/${path}"
      ];
    };
  };

  serialiseArg = key: val:
    lib.strings.concatStringsSep " "
    (lib.forEach (lib.toList val) (x: lib.strings.escapeShellArg "-${key}=${lib.escape ["="] x}"));
  serialiseArgs = args: lib.strings.concatStringsSep " " (lib.mapAttrsToList serialiseArg args);

  esa = a: lib.strings.escapeShellArg a;

  mkScriptLine = pathname: let
    path =
      mkPath pathname;
  in
    lib.strings.concatStringsSep " " [
      "unison"
      "${serialiseArgs unisonOptions}"
      "${esa path}"
      (esa "ssh://${config.home.username}@${hostName}.fritz.box/${path}")
    ];

  script = lib.strings.concatStringsSep "\n" (builtins.map mkScriptLine paths_to_keep);

  pairs = builtins.listToAttrs (builtins.map mkPair paths_to_keep);
in {
  home.packages = [
    (sysLib.writeShellScript {
      name = "unison-backup";
      src = builtins.toFile "unison-backup" (''
          #!/usr/bin/env sh
          export UNISON=${esa unisonPath};
        ''
        + script);
      dependencies = with pkgs; [unison openssh];
    })
  ];
  services.unison = {
    enable = false;
    inherit pairs;
  };
}