summaryrefslogtreecommitdiff
path: root/accounts/gkleen@sif/systemd.nix
blob: 20db64a056b8cf4afa6dde17085c84246db5c3de (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
{ pkgs, lib, config, userName, ... }:
let
  inherit (lib) listToAttrs nameValuePair;

  xmobar = import ./xmobar pkgs.haskellPackages;
  cfg = config.home-manager.users.${userName};

  autossh-socks-script = pkgs.writeScript "autossh" ''
    #!${pkgs.zsh}/bin/zsh -xe

    host="''${1%:*}"
    port="''${1#*:}"

    typeset -a cmd
    cmd=()

    if [[ -n "''${SSHPASS_SECRET}" ]]; then
      cmd+=(${pkgs.sshpassSecret}/bin/sshpass-secret)
      cmd+=("''${(@s/:/)SSHPASS_SECRET}")
      cmd+=(--)
    fi

    cmd+=(${pkgs.openssh}/bin/ssh -vN -D localhost:''${port} "''${host}")

    ( exec -a "''${cmd[1]}" -- ''${cmd} ) &
    pid=$!

    newpid=""
    i=200
    while ! newpid=$(${pkgs.lsof}/bin/lsof -Pi @localhost:"''${port}" -sTCP:LISTEN -t); do
      if ! kill -0 "''${pid}"; then
        wait "''${pid}"
        exit $?
      fi
      [[ "''${i}" -gt 0 ]] || exit 1
      i=$((''${i} - 1))
      ${pkgs.coreutils}/bin/sleep 0.1
    done

    ${config.systemd.package}/bin/systemd-notify --ready

    wait "''${pid}" "''${newpid}"
  '';
in {
  tmpfiles.rules = [
    "e /home/gkleen/screenshots - - - 365d -"
    "d /home/gkleen/.cache/qalc-fuzzel - - - 1d -"
  ];

  services = {
    sync-keepass = {
      Service = {
        Type = "oneshot";
        WorkingDirectory = "~";
        ExecStart = toString (pkgs.writers.writePython3 "sync-keepass" {
          libraries = with pkgs.python3Packages; [ python-dateutil ];
        } ''
          import json
          import subprocess
          from os.path import (expanduser, getmtime, dirname)
          from datetime import datetime
          from dateutil.tz import tzlocal
          from dateutil.parser import isoparse
          from sys import stderr


          remote_fs = 'surtr'
          remote_file = 'store.kdbx'
          target_file = expanduser('~/store.kdbx')
          meta_file = expanduser('~/.store.kdbx.json')

          upload_time = None
          our_last_upload_time = None
          mod_time = None


          def get_upload_time():
              upload_time = None
              with subprocess.Popen(['rclone', 'lsjson', f'{remote_fs}:{dirname(remote_file)}'], stdout=subprocess.PIPE) as proc:  # noqa: E501
                  for file in json.load(proc.stdout):
                      if file['Path'] != remote_file:
                          continue
                      else:
                          upload_time = isoparse(file['ModTime'])
                          break
              return upload_time


          def do_upload():
              print('Uploading', file=stderr)
              subprocess.run(['rclone', 'copy', '-I', target_file, f'{remote_fs}:{dirname(remote_file)}'], check=True)  # noqa: E501
              upload_time = get_upload_time()
              with open(meta_file, 'w') as file:
                  json.dump({'our_last_upload_time': upload_time.isoformat()}, file)


          def do_download():
              print('Downloading', file=stderr)
              subprocess.run(['rclone', 'copy', '-I', f'{remote_fs}:{remote_file}', dirname(target_file)], check=True)  # noqa: E501


          upload_time = get_upload_time()

          try:
              with open(meta_file, 'r') as file:
                  file_content = json.load(file)
                  our_last_upload_time = isoparse(file_content['our_last_upload_time'])  # noqa: E501
          except FileNotFoundError:
              pass

          try:
              mod_time = datetime.fromtimestamp(getmtime(target_file)).replace(tzinfo=tzlocal())  # noqa: E501
          except FileNotFoundError:
              pass

          if upload_time is None or (mod_time is not None and mod_time > upload_time):  # noqa: E501
              do_upload()
          elif upload_time is not None and (mod_time is None or upload_time > mod_time) and (our_last_upload_time is None or upload_time > our_last_upload_time):  # noqa: E501
              do_download()
        '');
        Environment = [ "RCLONE_PASSWORD_COMMAND=\"${pkgs.coreutils}/bin/cat ${config.sops.secrets.gkleen-rclone.path}\"" "PATH=${pkgs.rclone}/bin" ];
      };
    };
    emacs = {
      Unit = {
        After = ["graphical-session-pre.target"];
      };
    };
    dunst = {
      Service = {
        ExecStart = lib.mkForce "${cfg.services.dunst.package}/bin/dunst";
        Restart = "always";
      };
      Install = {
        WantedBy = ["graphical-session.target"];
      };
    };
    keepassxc = {
      Service = {
        Type = "dbus";
        BusName = "org.keepassxc.KeePassXC.MainWindow";
        WorkingDirectory = "~";
        ExecStart = "${pkgs.keepassxc}/bin/keepassxc";
        Environment = [ "QT_QPA_PLATFORM=wayland" ];
      };
      Unit = {
        Requires = ["graphical-session-pre.target"];
        After = ["graphical-session-pre.target"];
      };
    };
    mpris-proxy = {
      Unit.Description = "Mpris proxy";
      Unit.After = [ "network.target" "sound.target" ];
      Service.ExecStart = "${pkgs.bluez}/bin/mpris-proxy";
      Install.WantedBy = [ "default.target" ];
    };
    "autossh-socks@proxy.mathw0h:8119" = {
      Service = {
        Type = "notify";
        NotifyAccess = "all";
        WorkingDirectory = "~";
        Restart = "always";
        RestartSec = "23s";
        ExecStart = "${autossh-socks-script} \"%I\"";
        Environment = [ "SSHPASS_SECRET=gkleen@mathw0g.math.lmu.de" ];
      };
      Unit = {
        StopWhenUnneeded = true;
        StartLimitInterval = "180s";
        StartLimitBurst = 7;
      };
    };
    "autossh-socks@proxy.vidhar:8121" = {
      Service = {
        Type = "notify";
        NotifyAccess = "all";
        WorkingDirectory = "~";
        Restart = "always";
        RestartSec = "2s";
        ExecStart = "${autossh-socks-script} \"%I\"";
      };
      Unit = {
        StopWhenUnneeded = true;
      };
    };
    swayidle = {
      Service = {
        RuntimeDirectory = "swayidle";
      };
    };
    psi-notify = {
      Install = {
        WantedBy = ["graphical-session.target"];
      };
      Unit = {
        Requires = ["graphical-session-pre.target"];
        After = ["graphical-session-pre.target"];
      };
      Service = {
        ExecStart = lib.getExe pkgs.psi-notify;
        ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
        Type = "notify";
        Restart = "always";
        WatchdogSec = "2s";
      };
    };
    polkit-gnome-authentication-agent-1 = {
      Install = {
        WantedBy = ["graphical-session.target"];
      };
      Unit = {
        PartOf = ["graphical-session.target"];
        Requires = ["graphical-session-pre.target"];
        After = ["graphical-session-pre.target"];
      };
      Service = {
        ExecStart = "${pkgs.polkit_gnome}/libexec/polkit-gnome-authentication-agent-1";
        Restart = "on-failure";
      };
    };
    gtklock = {
      Unit = {
        Requisite = ["graphical-session.target"];
        PartOf = ["graphical-session.target"];
      };
      Service = {
        Type = "notify";
        RuntimeDirectory = "gtklock";
        CacheDirectory = "gtklock";
        ExecStartPre = [
          "${pkgs.libsForQt5.qt5.qttools.bin}/bin/qdbus org.keepassxc.KeePassXC.MainWindow /keepassxc org.keepassxc.KeePassXC.MainWindow.lockAllDatabases"
          "${config.systemd.package}/bin/systemctl --user stop gpg-agent.service"
          (pkgs.writeShellScript "generate-css" ''
            set -x
            export PATH="${lib.makeBinPath [cfg.programs.wpaperd.package pkgs.jq pkgs.coreutils pkgs.imagemagick pkgs.findutils]}:$PATH"

            declare -A monitors
            monitors=()
            while IFS= read -r entry; do
                path=$(jq -r ".path" <<<"$entry")
                [[ -z "$path" || ! -f "$path" ]] && continue
                blurred_path="$CACHE_DIRECTORY"/"$(b2sum -l 128 <<<"$path" | cut -d' ' -f1)"."''${path##*.}"
                monitor=$(jq -r ".display" <<<"$entry")
                if [[ ! -f "$blurred_path" ]]; then
                    mkdir -p "$(dirname "$blurred_path")"
                    magick "$path" -filter Gaussian -resize 6.25% -define filter:sigma=2.5 -resize 1600% "$blurred_path" &
                fi
                monitors+=([$monitor]="$blurred_path")
            done < <(wpaperctl all-wallpapers -j | jq -c ".[]")
            wait

            cp --no-preserve=mode ${pkgs.writeText "gtklock.css" ''
              #window-box {
                padding: 64px;
                /* border: 1px solid black; */
                border-radius: 4px;
                box-shadow: rgba(0, 0, 0, 0.8) 0px 4px 12px;
                /* background-color: white; */
                background-color: rgba(0, 0, 0, 0.5);
              }
            ''} "$RUNTIME_DIRECTORY"/style.css
            for monitor in "''${!monitors[@]}"; do
            cat >>"$RUNTIME_DIRECTORY"/style.css <<EOF
            window#''${monitor} {
              background-image: url("''${monitors[$monitor]}");
              background-repeat: no-repeat;
              background-size: 100% 100%;
              background-origin: content-box;
            }
            EOF
            done
          '')
        ];
        NotifyAccess = "all";
        ExecStart = ''${lib.getExe pkgs.gtklock} -s "''${RUNTIME_DIRECTORY}/style.css" -L ${pkgs.writeShellScript "after-lock" ''
          ${cfg.wayland.windowManager.hyprland.package}/bin/hyprctl dispatch dpms off
          ${config.systemd.package}/bin/systemd-notify --ready
        ''}'';
      };
    };
    "yt-dlp@" = {
      Service = {
        Type = "notify";
        CacheDirectory = "yt-dlp/%N";
        StandardInput = "socket";
        StandardOutput = "journal";
        WatchdogSec = "30min";
        Environment = [
          "PATH=${lib.makeBinPath (with pkgs; [atomicparsley ffmpeg-headless rtmpdump])}"
        ];
        ExecStart = pkgs.writers.writePython3 "yt-dlp" {
          libraries = with pkgs.python3Packages; [ yt-dlp sdnotify ];
        } ''
          import json
          from yt_dlp import YoutubeDL, parse_options
          from sys import stdin
          from sdnotify import SystemdNotifier
          from os import environ
          from pathlib import Path


          n = SystemdNotifier()
          args = json.load(stdin)
          ydl_opts = {
              **parse_options().ydl_opts,
              'progress_hooks': [lambda _d: n.notify('WATCHDOG=1')],
              'postprocessor_hooks': [lambda _d: n.notify('WATCHDOG=1')],
              'progress_with_newline': True,
              'progress_delta': 5,
              'paths': {
                  'home': str(Path.home() / 'media'),
                  'temp': str(Path(environ['CACHE_DIRECTORY'])),
              },
              **(args['params'] if 'params' in args else {}),
          }
          with YoutubeDL(ydl_opts) as ytdl:
              n.notify('READY=1')
              ytdl.download(args['urls'])
        '';
        ExecStopPost = "${pkgs.coreutils}/bin/rm -rfv \"$CACHE_DIRECTORY\"";
      };
    };
  } // listToAttrs (map ({host, port}: nameValuePair "proxy-to-autossh-socks@${toString port}" {
      Unit = {
        Requires = ["autossh-socks@${host}:${toString (port + 1)}.service" "proxy-to-autossh-socks@${toString port}.socket"];
        After = ["autossh-socks@${host}:${toString (port + 1)}.service" "proxy-to-autossh-socks@${toString port}.socket"];
      };
      Service = {
        ExecStart = "${config.systemd.package}/lib/systemd/systemd-socket-proxyd --exit-idle-time=10s localhost:${toString (port + 1)}";
      };
  }) [{ host = "proxy.mathw0h"; port = 8118; } { host = "proxy.vidhar"; port = 8120; }]);
  sockets = listToAttrs (map (port: nameValuePair "proxy-to-autossh-socks@${toString port}" {
    Socket = {
      ListenStream = "%I";
    };
    Install = {
      WantedBy = ["default.target"];
    };
  }) [8118 8120]) // {
    "yt-dlp" = {
      Socket = {
        SocketMode = "0600";
        Accept = true;
        ListenStream = "%t/yt-dlp.sock";
        TriggerLimitIntervalSec = 0;
      };
      Install = {
        WantedBy = ["sockets.target"];
      };
    };
  };
  timers = {
    sync-keepass = {
      Timer = {
        OnActiveSec = "1m";
        OnUnitActiveSec = "1m";
      };

      Install = {
        WantedBy = ["default.target"];
      };
    };
  };
  targets = {
    graphical-session = {
      Unit = {
        BindsTo = ["default.target"];
        After = ["basic.target"];
      };
    };
    tray = {
      Unit = {
        Wants = ["blueman-applet.service" "udiskie.service" "network-manager-applet.service"];
      };
    };
  };
}