main
1{
2 libx,
3 globals,
4 lib,
5 pkgs,
6 config,
7 ...
8}:
9
10let
11 # Service defaults for media/homelab services
12 serviceDefaults = libx.mkServiceDefaults { };
13
14 # Samba shares configuration (data-driven approach)
15 # Samba shares on /neo
16 neoSambaShares = {
17 backup = { };
18 downloads = { };
19 pictures = { };
20 videos = { };
21 };
22 # Samba shares on /zion
23 zionSambaShares = {
24 audiobooks = {
25 readOnly = true;
26 };
27 ebooks = { };
28 documents = { };
29 music = {
30 readOnly = true;
31 };
32 };
33
34 # Exportarr services configuration (data-driven approach)
35 exportarrServices = {
36 sonarr = {
37 port = 9707;
38 servicePort = 8989;
39 };
40 radarr = {
41 port = 9708;
42 servicePort = 7878;
43 };
44 lidarr = {
45 port = 9709;
46 servicePort = 8686;
47 };
48 prowlarr = {
49 port = 9710;
50 servicePort = 9696;
51 };
52 bazarr = {
53 port = 9712;
54 servicePort = 6767;
55 };
56 };
57
58 # Common rsync configuration for aion backups (reverse sync after migration)
59 aionBackupDefaults = {
60 source = {
61 host = "aion.sbr.pm";
62 user = "vincent";
63 };
64 destination = "/zion";
65 delete = true; # Mirror mode: delete files in destination that don't exist in source
66 user = "vincent";
67 group = "users";
68 rsyncArgs = [
69 "--exclude=.Trash-*"
70 "--exclude=lost+found"
71 ];
72 sshArgs = [
73 "-o StrictHostKeyChecking=accept-new"
74 ];
75 };
76in
77{
78 nixpkgs.config.permittedInsecurePackages = [
79 "python3.13-beets-2.5.1"
80 ];
81
82 imports = [
83 ../common/services/samba.nix
84
85 ../common/services/prometheus-exporters-postgres.nix
86 ../../modules/jellyfin-auto-collections
87 ../../modules/jellyfin-favorites-sync
88 ];
89
90 # Age secrets: gandi.env + webdav + jellyfin + ollama + generated exportarr secrets
91 age.secrets = {
92 "gandi.env" = {
93 file = ../../secrets/rhea/gandi.env.age;
94 mode = "400";
95 owner = "traefik";
96 group = "traefik";
97 };
98 "joplin.env" = {
99 file = ../../secrets/rhea/joplin.env.age;
100 mode = "400";
101 };
102 "webdav-password" = {
103 file = ../../secrets/rhea/webdav-password.age;
104 mode = "400";
105 };
106 "jellyfin-auto-collections-api-key" = {
107 file = ../../secrets/rhea/jellyfin-auto-collections-api-key.age;
108 mode = "400";
109 owner = "jellyfin-auto-collections";
110 };
111 "jellyfin-auto-collections-jellyseerr-password" = {
112 file = ../../secrets/rhea/jellyfin-auto-collections-jellyseerr-password.age;
113 mode = "400";
114 owner = "jellyfin-auto-collections";
115 };
116 "jellyfin-favorites-sync-api-key" = {
117 file = ../../secrets/rhea/jellyfin-favorites-sync-api-key.age;
118 mode = "400";
119 owner = "jellyfin-favorites-sync";
120 };
121 "jellyfin-favorites-sync-ssh-key" = {
122 file = ../../secrets/rhea/jellyfin-favorites-sync-ssh-key.age;
123 mode = "400";
124 owner = "jellyfin-favorites-sync";
125 };
126 "restic-aix-password" = {
127 file = ../../secrets/rhea/restic-aix-password.age;
128 mode = "400";
129 owner = "vincent";
130 group = "users";
131 };
132 "ntfy-token" = {
133 file = ../../secrets/sakhalin/ntfy-token.age;
134 mode = "400";
135 owner = "vincent";
136 group = "users";
137 };
138 }
139 // lib.mapAttrs' (
140 name: _cfg:
141 lib.nameValuePair "exportarr-${name}-apikey" {
142 file = ../../secrets/rhea/exportarr-${name}-apikey.age;
143 mode = "400";
144 owner = "root";
145 }
146 ) exportarrServices;
147
148 users.users.vincent.linger = true;
149
150 services = {
151 traefik = {
152 enable = true;
153
154 staticConfigOptions = {
155 # API and Dashboard
156 api = {
157 dashboard = true;
158 insecure = false;
159 };
160
161 # Prometheus metrics
162 metrics.prometheus = {
163 addEntryPointsLabels = true;
164 addRoutersLabels = true;
165 addServicesLabels = true;
166 };
167
168 # Entry points
169 entryPoints = {
170 web = {
171 address = ":80";
172 http.redirections.entryPoint = {
173 to = "websecure";
174 scheme = "https";
175 };
176 };
177 websecure = {
178 address = ":443";
179 transport = {
180 respondingTimeouts = {
181 readTimeout = "600s"; # 10 minutes for large uploads
182 writeTimeout = "600s";
183 idleTimeout = "600s";
184 };
185 };
186 };
187 mqtt = {
188 address = ":1883";
189 };
190 mqtts = {
191 address = ":8883";
192 };
193 };
194
195 # Certificate resolver using Gandi DNS
196 certificatesResolvers.letsencrypt = {
197 acme = {
198 email = "vincent@sbr.pm";
199 storage = "/var/lib/traefik/acme.json";
200 dnsChallenge = {
201 provider = "gandiv5";
202 delayBeforeCheck = "0s";
203 resolvers = [
204 "1.1.1.1:53"
205 "8.8.8.8:53"
206 ];
207 };
208 };
209 };
210 };
211
212 # Dynamic configuration using module option
213 dynamicConfigOptions =
214 let
215 # Helper function to create a simple HTTP router
216 mkRouter = name: hosts: {
217 rule = lib.concatStringsSep " || " (map (host: "Host(`${host}`)") hosts);
218 service = name;
219 entryPoints = [ "websecure" ];
220 tls.certResolver = "letsencrypt";
221 };
222
223 # Helper function to create a router with middlewares
224 mkRouterWithMiddlewares = name: hosts: middlewares: {
225 rule = lib.concatStringsSep " || " (map (host: "Host(`${host}`)") hosts);
226 service = name;
227 entryPoints = [ "websecure" ];
228 tls.certResolver = "letsencrypt";
229 inherit middlewares;
230 };
231
232 # Helper function to create a simple HTTP service
233 mkService = url: {
234 loadBalancer.servers = [ { inherit url; } ];
235 };
236
237 # Define local services with their ports and optional alternate hosts
238 localServices = {
239 jellyfin.port = 8096;
240 jellyseerr.port = 5055;
241 # *arr services - ports from exportarrServices
242 sonarr.port = exportarrServices.sonarr.servicePort;
243 radarr.port = exportarrServices.radarr.servicePort;
244 bazarr.port = exportarrServices.bazarr.servicePort;
245 prowlarr.port = exportarrServices.prowlarr.servicePort;
246 transmission = {
247 port = 9091;
248 altHosts = [ "t.sbr.pm" ];
249 };
250 immich.port = 2283;
251 liseur = {
252 port = 8585;
253 altHosts = [ "books.sbr.pm" ];
254 };
255 dav.port = 6065;
256 joplin.port = 22300;
257 };
258
259 # Generate routers for local services
260 localRouters = lib.mapAttrs' (
261 name: cfg:
262 let
263 hosts = [ "${name}.sbr.pm" ] ++ (cfg.altHosts or [ ]);
264 in
265 lib.nameValuePair name (mkRouter name hosts)
266 ) localServices;
267
268 # Generate services for local services
269 localHttpServices = lib.mapAttrs' (
270 name: cfg: lib.nameValuePair name (mkService "http://localhost:${toString cfg.port}")
271 ) localServices;
272
273 # Filter machines that have syncthing configured
274 syncthingMachines = lib.filterAttrs (
275 _name: machine: machine ? syncthing && machine.syncthing ? folders
276 ) globals.machines;
277
278 # Generate routers for syncthing hosts
279 syncthingRouters = lib.mapAttrs' (
280 name: _machine:
281 lib.nameValuePair "syncthing-${name}" {
282 rule = "Host(`syncthing.sbr.pm`) && PathPrefix(`/${name}`) || Host(`s.sbr.pm`) && PathPrefix(`/${name}`)";
283 service = "syncthing-${name}";
284 entryPoints = [ "websecure" ];
285 middlewares = [
286 "syncthing-${name}-addslash"
287 "syncthing-${name}-strip"
288 ];
289 tls = {
290 certResolver = "letsencrypt";
291 };
292 }
293 ) syncthingMachines;
294
295 # Generate services for syncthing hosts
296 syncthingServices = lib.mapAttrs' (
297 name: machine:
298 lib.nameValuePair "syncthing-${name}" {
299 loadBalancer = {
300 servers = [
301 { url = "http://${builtins.head machine.net.vpn.ips}:8384"; }
302 ];
303 };
304 }
305 ) syncthingMachines;
306
307 # Generate middleware for path stripping
308 syncthingMiddlewares = lib.mapAttrs' (
309 name: _machine:
310 lib.nameValuePair "syncthing-${name}-strip" {
311 stripPrefix = {
312 prefixes = [ "/${name}" ];
313 };
314 }
315 ) syncthingMachines;
316
317 # Generate middleware for adding trailing slash
318 syncthingAddSlashMiddlewares = lib.mapAttrs' (
319 name: _machine:
320 lib.nameValuePair "syncthing-${name}-addslash" {
321 redirectRegex = {
322 regex = "^(https?://[^/]+/${name})$";
323 replacement = "$$1/";
324 permanent = true;
325 };
326 }
327 ) syncthingMachines;
328 in
329 {
330 http = {
331 routers =
332 syncthingRouters
333 // localRouters
334 // {
335 joplin = mkRouterWithMiddlewares "joplin" [ "joplin.sbr.pm" ] [ "joplin-allowlist" ];
336 # Override immich router to add large file upload middleware
337 immich = mkRouterWithMiddlewares "immich" [ "immich.sbr.pm" ] [ "immich-buffering" ];
338 # Override home router to add Home Assistant headers
339 home = mkRouterWithMiddlewares "home" [ "home.sbr.pm" ] [ "home-headers" ];
340 paperless = mkRouter "paperless" [ "paperless.sbr.pm" ];
341 grafana = mkRouter "grafana" [ "grafana.sbr.pm" ];
342 navidrome = mkRouter "navidrome" [
343 "navidrome.sbr.pm"
344 "music.sbr.pm"
345 ];
346 transmission-music = mkRouter "transmission-music" [
347 "transmission-music.sbr.pm"
348 "tm.sbr.pm"
349 ];
350 audiobookshelf = mkRouter "audiobookshelf" [
351 "audiobookshelf.sbr.pm"
352 "podcasts.sbr.pm"
353 ];
354 lidarr = mkRouter "lidarr" [ "lidarr.sbr.pm" ];
355 wallabag = mkRouter "wallabag" [
356 "wallabag.sbr.pm"
357 "read.sbr.pm"
358 ];
359 miniflux = mkRouter "miniflux" [
360 "miniflux.sbr.pm"
361 "rss.sbr.pm"
362 ];
363 homepage = mkRouter "homepage" [ "homepage.sbr.pm" ];
364 # OpenCode web interface on okinawa (VPN-only)
365 opencode = mkRouter "opencode" [ "opencode.sbr.pm" ];
366 reading = mkRouter "reading" [ "reading.sbr.pm" ];
367 # Traefik dashboard
368 traefik-dashboard = {
369 rule = "Host(`traefik.sbr.pm`)";
370 service = "api@internal";
371 entryPoints = [ "websecure" ];
372 tls.certResolver = "letsencrypt";
373 };
374 };
375 services =
376 syncthingServices
377 // localHttpServices
378 // {
379 home = mkService "http://${builtins.head globals.machines.hass.net.ips}:8123";
380 paperless = mkService "http://${builtins.head globals.machines.aion.net.ips}:8000";
381 grafana = mkService "http://${builtins.head globals.machines.sakhalin.net.ips}:3000";
382 navidrome = mkService "http://${builtins.head globals.machines.aion.net.ips}:4533";
383 transmission-music = mkService "http://${builtins.head globals.machines.aion.net.ips}:9091";
384 homepage = mkService "http://${builtins.head globals.machines.aion.net.ips}:3001";
385 audiobookshelf = mkService "http://${builtins.head globals.machines.aion.net.ips}:13378";
386 lidarr = mkService "http://${builtins.head globals.machines.aion.net.ips}:8686";
387 wallabag = mkService "http://${builtins.head globals.machines.aion.net.ips}:8084";
388 miniflux = mkService "http://${builtins.head globals.machines.aion.net.ips}:8085";
389 opencode = mkService "http://${builtins.head globals.machines.okinawa.net.vpn.ips}:5555";
390 reading = mkService "http://${builtins.head globals.machines.okinawa.net.vpn.ips}:8880";
391 };
392 middlewares =
393 syncthingMiddlewares
394 // syncthingAddSlashMiddlewares
395 // {
396 joplin-allowlist.ipAllowList.sourceRange = globals.net.dns.cacheNetworks;
397 # Middleware for handling large file uploads (Immich)
398 immich-buffering = {
399 buffering = {
400 maxRequestBodyBytes = 0; # No limit
401 memRequestBodyBytes = 104857600; # 100MB in memory
402 maxResponseBodyBytes = 0; # No limit
403 memResponseBodyBytes = 104857600; # 100MB in memory
404 retryExpression = "IsNetworkError() && Attempts() < 2";
405 };
406 };
407 # Middleware for Home Assistant reverse proxy headers
408 home-headers = {
409 headers = {
410 customRequestHeaders = {
411 X-Forwarded-Proto = "https";
412 };
413 };
414 };
415 };
416 };
417 tcp = {
418 routers = {
419 mqtt = {
420 rule = "HostSNI(`*`)";
421 service = "mqtt";
422 entryPoints = [ "mqtt" ];
423 };
424 mqtts = {
425 rule = "HostSNI(`mqtt.sbr.pm`)";
426 service = "mqtt";
427 entryPoints = [ "mqtts" ];
428 tls = {
429 certResolver = "letsencrypt";
430 };
431 };
432 };
433 services = {
434 mqtt = {
435 loadBalancer = {
436 servers = [
437 { address = "${builtins.head globals.machines.demeter.net.ips}:1883"; }
438 ];
439 };
440 };
441 };
442 };
443 };
444 };
445
446 # smartd = {
447 # enable = true;
448 # devices = [ { device = "/dev/nvme0n1"; } ];
449 # };
450 samba.settings = {
451 global."server string" = "Rhea";
452 }
453 // builtins.mapAttrs (
454 name: cfg:
455 libx.mkSambaShare (
456 {
457 inherit name;
458 path = "/neo/${name}";
459 }
460 // cfg
461 )
462 ) neoSambaShares
463 // builtins.mapAttrs (
464 name: cfg:
465 libx.mkSambaShare (
466 {
467 inherit name;
468 path = "/zion/${name}";
469 }
470 // cfg
471 )
472 ) zionSambaShares;
473 nfs.server = {
474 enable = true;
475 # Fixed ports for firewall configuration
476 lockdPort = 4001;
477 mountdPort = 4002;
478 statdPort = 4000;
479 exports = ''
480 /neo 192.168.1.0/24(rw,fsid=0,no_subtree_check) 192.168.10.0/24(rw,fsid=0,no_subtree_check) 10.100.0.0/24(rw,fsid=0,no_subtree_check)
481 /neo/backup 192.168.1.0/24(rw,fsid=2,no_subtree_check) 192.168.10.0/24(rw,fsid=2,no_subtree_check) 10.100.0.0/24(rw,fsid=2,no_subtree_check)
482 /neo/downloads 192.168.1.0/24(rw,fsid=4,no_subtree_check) 192.168.10.0/24(rw,fsid=4,no_subtree_check) 10.100.0.0/24(rw,fsid=4,no_subtree_check)
483 /neo/pictures 192.168.1.0/24(rw,fsid=7,no_subtree_check) 192.168.10.0/24(rw,fsid=7,no_subtree_check) 10.100.0.0/24(rw,fsid=7,no_subtree_check)
484 /neo/videos 192.168.1.0/24(rw,fsid=8,no_subtree_check) 192.168.10.0/24(rw,fsid=8,no_subtree_check) 10.100.0.0/24(rw,fsid=8,no_subtree_check)
485 /zion 192.168.1.0/24(rw,fsid=10,no_subtree_check) 192.168.10.0/24(rw,fsid=10,no_subtree_check) 10.100.0.0/24(rw,fsid=10,no_subtree_check)
486 /zion/audiobooks 192.168.1.0/24(ro,fsid=11,no_subtree_check) 192.168.10.0/24(ro,fsid=11,no_subtree_check) 10.100.0.0/24(ro,fsid=11,no_subtree_check)
487 /zion/documents 192.168.1.0/24(rw,fsid=12,no_subtree_check) 192.168.10.0/24(rw,fsid=12,no_subtree_check) 10.100.0.0/24(rw,fsid=12,no_subtree_check)
488 /zion/ebooks 192.168.1.0/24(rw,fsid=13,no_subtree_check) 192.168.10.0/24(rw,fsid=13,no_subtree_check) 10.100.0.0/24(rw,fsid=13,no_subtree_check)
489 /zion/music 192.168.1.0/24(ro,fsid=14,no_subtree_check) 192.168.10.0/24(ro,fsid=14,no_subtree_check) 10.100.0.0/24(ro,fsid=14,no_subtree_check)
490 '';
491 };
492 immich = serviceDefaults // {
493 enable = true;
494 host = "0.0.0.0"; # Listen on all interfaces for VPN access
495 mediaLocation = "/neo/pictures/photos";
496 package = pkgs.unstable.immich; # 26.05 ships insecure immich 2.x
497 };
498 postgresql = {
499 package = pkgs.postgresql_16;
500 authentication = lib.mkBefore ''
501 local joplin joplin scram-sha-256
502 '';
503 ensureDatabases = [
504 "immich"
505 "joplin"
506 ];
507 ensureUsers = [
508 {
509 name = "vincent";
510 }
511 {
512 name = "joplin";
513 ensureDBOwnership = true;
514 }
515 ];
516 };
517 jellyfin = serviceDefaults // {
518 enable = true;
519 };
520 jellyseerr = {
521 enable = true;
522 openFirewall = true;
523 };
524 webdav = {
525 enable = true;
526 user = "vincent";
527 group = "users";
528 environmentFile = config.age.secrets."webdav-password".path;
529 settings = {
530 address = "127.0.0.1";
531 port = 6065;
532 scope = "/zion/documents/boox";
533 modify = true;
534 users = [
535 {
536 username = "vincent";
537 password = "{env}WEBDAV_PASSWORD_HASH";
538 }
539 ];
540 rules = [
541 {
542 regex = "(\\..*|.*\\.tmp)$"; # Block hidden files and .tmp files
543 allow = false;
544 }
545 ];
546 };
547 };
548 jellyfin-auto-collections = {
549 enable = true;
550 jellyfinUrl = "http://localhost:8096";
551 userId = "400fef4e0ab2448cb8a2bc8ca2facc4f";
552 apiKeyFile = config.age.secrets."jellyfin-auto-collections-api-key".path;
553 schedule = "daily"; # Run daily at midnight
554
555 jellyseerr = {
556 enable = false; # Enable when password secret is created
557 serverUrl = "http://localhost:5055";
558 email = "vincent@sbr.pm";
559 # Uncomment when jellyseerr password secret is created
560 # passwordFile = config.age.secrets."jellyfin-auto-collections-jellyseerr-password".path;
561 userType = "local";
562 };
563
564 settings = {
565 plugins = {
566 imdb_chart = {
567 enabled = true;
568 list_ids = [
569 "top"
570 "moviemeter"
571 ];
572 clear_collection = true;
573 };
574 imdb_list = {
575 enabled = true;
576 list_ids = [
577 "ls055592025" # IMDb Top 250
578 ];
579 };
580 jellyfin_api = {
581 enabled = true;
582 list_ids = [
583 # Marvel Cinematic Universe
584 {
585 studios = [
586 "Marvel Studios"
587 "Marvel Entertainment"
588 ];
589 list_name = "Marvel Cinematic Universe";
590 includeItemTypes = [ "Movie" ];
591 }
592 # Pixar Animation
593 {
594 studios = [ "Pixar" ];
595 list_name = "Pixar Collection";
596 includeItemTypes = [ "Movie" ];
597 }
598 # Studio Ghibli
599 {
600 studios = [ "Studio Ghibli" ];
601 list_name = "Studio Ghibli Collection";
602 includeItemTypes = [ "Movie" ];
603 }
604 # Sing Movies (Illumination)
605 {
606 searchTerm = "Sing";
607 studios = [ "Illumination Entertainment" ];
608 list_name = "Sing Movies";
609 includeItemTypes = [ "Movie" ];
610 }
611 # Christopher Nolan Films
612 {
613 person = [ "Christopher Nolan" ];
614 list_name = "Christopher Nolan Collection";
615 includeItemTypes = [ "Movie" ];
616 }
617 # Highly Rated Sci-Fi
618 {
619 genres = [ "Science Fiction" ];
620 minCriticRating = [ "8" ];
621 list_name = "Top Sci-Fi Movies";
622 includeItemTypes = [ "Movie" ];
623 }
624 # Recent Movies (2024-2025)
625 {
626 years = [
627 2024
628 2025
629 ];
630 list_name = "Recent Releases";
631 includeItemTypes = [ "Movie" ];
632 }
633 # Award Winners
634 {
635 tags = [ "Oscar Winner" ];
636 list_name = "Oscar Winners";
637 includeItemTypes = [ "Movie" ];
638 }
639 ];
640 };
641 };
642 };
643 };
644 jellyfin-favorites-sync = {
645 enable = true;
646 schedule = "daily"; # Run daily at midnight
647
648 jellyfinUrl = "http://localhost:8096";
649 apiKeyFile = config.age.secrets."jellyfin-favorites-sync-api-key".path;
650 userId = "400fef4e0ab2448cb8a2bc8ca2facc4f"; # vincent user ID
651
652 # Use "Keep" playlist instead of favorites
653 playlistName = "Keep";
654
655 sourceRoot = "/neo/videos";
656
657 destination = {
658 host = "aix.sbr.pm";
659 user = "vincent";
660 root = "/data/videos";
661 };
662
663 # SSH key for authentication
664 sshKeyFile = config.age.secrets."jellyfin-favorites-sync-ssh-key".path;
665
666 sshArgs = [
667 "-o StrictHostKeyChecking=no"
668 "-o UserKnownHostsFile=/dev/null"
669 ];
670
671 # Dry-run verified, now syncing for real
672 dryRun = false;
673 };
674 transmission = serviceDefaults // {
675 enable = true;
676 package = pkgs.transmission_4;
677 openRPCPort = true; # Open firewall for RPC
678 home = "/neo/torrents";
679 settings = {
680 # Override default settings
681 incomplete-dir-enabled = true;
682 rpc-bind-address = "0.0.0.0"; # Bind to own IP
683 rpc-host-whitelist = "localhost,t.sbr.pm,transmission.sbr.pm,rhea.home,rhea.vpn,rhea.sbr.pm,192.168.10.231,10.100.0.50";
684 rpc-host-whitelist-enabled = true;
685 rpc-whitelist-enabled = true;
686 rpc-whitelist = "127.0.0.1,192.168.1.*,192.168.10.*,10.100.0.*"; # Whitelist your remote machine (10.0.0.1 in this example)
687 rpc-username = "transmission";
688 rpc-password = "transmission";
689 download-queue-enabled = true;
690 download-queue-size = 15;
691 queue-stalled-enabled = true;
692 queue-stalled-minutes = 30;
693 ratio-limit = 0.1;
694 ratio-limit-enabled = true;
695 };
696 };
697 # *arr services - ports configured via exportarrServices
698 sonarr = serviceDefaults // {
699 enable = true;
700 settings.server.port = exportarrServices.sonarr.servicePort;
701 };
702 radarr = serviceDefaults // {
703 enable = true;
704 settings.server.port = exportarrServices.radarr.servicePort;
705 };
706 bazarr = serviceDefaults // {
707 enable = true;
708 listenPort = exportarrServices.bazarr.servicePort;
709 };
710 prowlarr = {
711 enable = true;
712 openFirewall = true;
713 settings.server.port = exportarrServices.prowlarr.servicePort;
714 };
715
716 # Rsync replica jobs to backup FROM aion (disabled until migration)
717 rsync-replica = {
718 enable = true; # Enable after audio services migration to aion
719 jobs = {
720 aion-music-hourly = aionBackupDefaults // {
721 source = aionBackupDefaults.source // {
722 paths = [ "/zion/music" ];
723 };
724 schedule = "hourly";
725 };
726 aion-audiobooks-daily = aionBackupDefaults // {
727 source = aionBackupDefaults.source // {
728 paths = [ "/zion/audiobooks" ];
729 };
730 schedule = "daily";
731 };
732 };
733 };
734
735 # Generate prometheus exporters for all exportarr services
736 prometheus.exporters = lib.mapAttrs' (
737 name: cfg:
738 lib.nameValuePair "exportarr-${name}" {
739 enable = true;
740 inherit (cfg) port;
741 url = "http://localhost:${toString cfg.servicePort}";
742 apiKeyFile = config.age.secrets."exportarr-${name}-apikey".path;
743 }
744 ) exportarrServices;
745
746 # Stream a fresh consistent PostgreSQL dump directly to restic. A failed
747 # pg_dump fails the backup; there is no on-disk dump that can become stale.
748 restic.backups.aix-joplin = {
749 user = "vincent";
750 repository = "sftp:vincent@aix.sbr.pm:/data/backup/restic/rhea";
751 passwordFile = config.age.secrets."restic-aix-password".path;
752 command = [
753 "${config.services.postgresql.package}/bin/pg_dump"
754 "--format=custom"
755 "--dbname=joplin"
756 ];
757 extraBackupArgs = [
758 "--stdin-filename=joplin.dump"
759 "--tag=joplin"
760 ];
761 timerConfig = {
762 OnCalendar = "daily";
763 Persistent = true;
764 RandomizedDelaySec = "2h";
765 };
766 pruneOpts = [
767 "--keep-daily 7"
768 "--keep-weekly 4"
769 "--keep-monthly 12"
770 "--group-by host,paths,tags"
771 "--tag joplin"
772 ];
773 };
774
775 # Restic backup to aix (off-site backup)
776 # Note: Media files are rsync'd (rhea → aion → aix)
777 # This backup focuses on arr service databases and configs
778 restic.backups.aix-critical = {
779 user = "vincent";
780 repository = "sftp:vincent@aix.sbr.pm:/data/backup/restic/rhea";
781
782 # Use password-based encryption
783 passwordFile = config.age.secrets."restic-aix-password".path;
784
785 paths = [
786 "/var/lib/sonarr" # Sonarr database and config (~501MB)
787 "/var/lib/radarr" # Radarr database and config (~729MB)
788 "/var/lib/bazarr" # Bazarr database and config (~25MB)
789 "/var/lib/readarr" # Readarr database and config (~6MB)
790 "/var/lib/prowlarr" # Prowlarr database and config
791 "/var/lib/jellyfin" # Jellyfin database and config
792 "/var/lib/liseur-sync" # Liseur Sync database, accounts, and reading state
793 # "/var/lib/immich" # Immich app data # Already handled in aion
794 # "/var/lib/traefik" # Traefik acme.json (Let's Encrypt certs)
795 ];
796
797 # Backup schedule - weekly for moderate dataset
798 timerConfig = {
799 OnCalendar = "weekly";
800 Persistent = true;
801 RandomizedDelaySec = "2h"; # Avoid conflict with aion backup
802 };
803
804 # Retention policy
805 pruneOpts = [
806 "--keep-daily 7" # Last 7 days
807 "--keep-weekly 4" # Last 4 weeks
808 "--keep-monthly 12" # Last 12 months
809 "--keep-yearly 3" # Last 3 years
810 ];
811
812 # Backup options
813 extraBackupArgs = [
814 "--exclude-caches"
815 "--exclude='*.Trash-*'"
816 "--exclude='lost+found'"
817 "--exclude='logs.db'" # Exclude log databases (large, not critical)
818 "--verbose"
819 ];
820
821 # Check repository integrity after backup
822 checkOpts = [
823 "--read-data-subset=5%" # Verify 5% of data each run
824 ];
825
826 # Backup monitoring with ntfy.sh
827 backupPrepareCommand = ''
828 ${pkgs.curl}/bin/curl \
829 -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
830 config.age.secrets."ntfy-token".path
831 })" \
832 -H "Title: Restic Backup Starting (rhea)" \
833 -d "Starting backup to aix (arr services + configs)" \
834 https://ntfy.sbr.pm/backups
835 '';
836
837 backupCleanupCommand = ''
838 ${pkgs.curl}/bin/curl \
839 -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
840 config.age.secrets."ntfy-token".path
841 })" \
842 -H "Title: Restic Backup Complete (rhea)" \
843 -H "Tags: white_check_mark" \
844 -d "Backup to aix completed successfully" \
845 https://ntfy.sbr.pm/backups || \
846 ${pkgs.curl}/bin/curl \
847 -H "Authorization: Bearer $(${pkgs.coreutils}/bin/tr -d '\n' < ${
848 config.age.secrets."ntfy-token".path
849 })" \
850 -H "Title: Restic Backup Failed (rhea)" \
851 -H "Tags: x,warning" \
852 -H "Priority: high" \
853 -d "Backup to aix failed! Check logs: journalctl -u restic-backups-aix-critical.service" \
854 https://ntfy.sbr.pm/backups
855 '';
856 };
857 };
858
859 security.acme = {
860 acceptTerms = true;
861 defaults.email = "vincent@sbr.pm";
862 };
863
864 # Grant vincent ownership and superuser privileges for the immich database
865 # Grant healthchecks user permissions for the healthchecks database
866 systemd.services.postgresql.postStart = lib.mkAfter ''
867 PSQL="${config.services.postgresql.package}/bin/psql --port=${toString config.services.postgresql.settings.port}"
868 $PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname = 'vincent'" | grep -q 1 || $PSQL -tAc "CREATE ROLE vincent WITH LOGIN SUPERUSER"
869 $PSQL -tAc "ALTER ROLE vincent WITH SUPERUSER"
870 $PSQL -tAc "ALTER DATABASE immich OWNER TO vincent"
871 $PSQL immich -tAc "ALTER SCHEMA public OWNER TO vincent"
872 $PSQL immich -tAc "GRANT ALL PRIVILEGES ON SCHEMA public TO vincent"
873 $PSQL immich -tAc "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO vincent"
874 $PSQL immich -tAc "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO vincent"
875 $PSQL immich -tAc "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO vincent"
876 '';
877
878 # Set the dedicated role's password without putting it in the Nix store or
879 # process arguments. The generated secret contains only a hex password.
880 systemd.services.joplin-db-password = {
881 requires = [ "postgresql-setup.service" ];
882 after = [ "postgresql-setup.service" ];
883 before = [ "podman-joplin.service" ];
884 serviceConfig = {
885 Type = "oneshot";
886 EnvironmentFile = config.age.secrets."joplin.env".path;
887 };
888 script = ''
889 case "$POSTGRES_PASSWORD" in
890 ""|*[!0-9a-f]*) exit 1 ;;
891 esac
892 printf "ALTER ROLE joplin PASSWORD '%s';\n" "$POSTGRES_PASSWORD" | \
893 ${pkgs.util-linux}/bin/runuser -u postgres -- ${config.services.postgresql.package}/bin/psql -v ON_ERROR_STOP=1 -d postgres
894 '';
895 };
896 systemd.services.podman-joplin = {
897 requires = [ "joplin-db-password.service" ];
898 after = [ "joplin-db-password.service" ];
899 };
900 systemd.services.restic-backups-aix-joplin = {
901 requires = [ "postgresql.service" ];
902 after = [ "postgresql.service" ];
903 };
904
905 # Liseur Sync indexes the Calibre library and synchronizes reader state.
906 virtualisation.podman.enable = true;
907 virtualisation.oci-containers = {
908 backend = "podman";
909 containers.joplin = {
910 image = "docker.io/joplin/server@sha256:1cd9097ec3f788ba9813b7907dd8d525c834b93c725da1add189bfd08f746cf0";
911 environment = {
912 APP_BASE_URL = "https://joplin.sbr.pm";
913 APP_PORT = "22300";
914 DB_CLIENT = "pg";
915 POSTGRES_DATABASE = "joplin";
916 POSTGRES_USER = "joplin";
917 POSTGRES_HOST = "/var/run/postgresql";
918 POSTGRES_PORT = toString config.services.postgresql.settings.port;
919 };
920 environmentFiles = [ config.age.secrets."joplin.env".path ];
921 extraOptions = [
922 "--cap-drop=ALL"
923 "--security-opt=no-new-privileges"
924 ];
925 ports = [ "127.0.0.1:22300:22300" ];
926 volumes = [ "/run/postgresql:/var/run/postgresql" ];
927 };
928 containers.liseur-sync = {
929 image = "ghcr.io/chmouel/liseur-sync@sha256:5015b61a6ac32eea9fdaa641b15c9a6234a4700b9d2a8a07ffcba2485efdaf24";
930 pull = "newer";
931 cmd = [ "serve" ];
932 environment = {
933 LISEUR_LISTEN_ADDR = "127.0.0.1:8585";
934 LISEUR_DATABASE_DRIVER = "sqlite";
935 LISEUR_DATABASE_URL = "/data/liseur-sync.db";
936 LISEUR_CACHE_DIR = "/data/cache";
937 LISEUR_FOLDER_ROOTS = "/books";
938 LISEUR_TRUSTED_PROXIES = "127.0.0.1/32,::1/128";
939 };
940 extraOptions = [ "--network=host" ];
941 volumes = [
942 "/var/lib/liseur-sync:/data"
943 "/zion/ebooks:/books:ro"
944 ];
945 };
946 };
947
948 systemd.tmpfiles.rules = [
949 "d /var/lib/liseur-sync 0750 65532 65532 -"
950 ];
951
952 networking.useDHCP = lib.mkDefault true;
953
954 # Open firewall for Traefik and NFS
955 networking.firewall = {
956 allowedTCPPorts = [
957 80
958 443
959 1883 # MQTT
960 8883 # MQTTS
961 8080 # Traefik metrics
962 9000 # Node exporter
963 9187 # PostgreSQL exporter
964 # Exportarr exporters
965 9707 # Sonarr
966 9708 # Radarr
967 9710 # Prowlarr
968 9712 # Bazarr
969 # NFS ports
970 111 # rpcbind
971 2049 # NFS daemon
972 4000 # statd
973 4001 # lockd
974 4002 # mountd
975 20048 # mountd (NFSv4)
976 ];
977 allowedUDPPorts = [
978 # NFS ports
979 111 # rpcbind
980 2049 # NFS daemon
981 4000 # statd
982 4001 # lockd
983 4002 # mountd
984 20048 # mountd (NFSv4)
985 ];
986 };
987
988 # Add ffsubsync and ffmpeg to bazarr's PATH for subtitle synchronization
989 systemd.services.bazarr.path = with pkgs; [
990 ffsubsync
991 ffmpeg-full
992 ];
993
994 # Environment file for Gandi API key (managed by agenix)
995 systemd.services.traefik.serviceConfig = {
996 EnvironmentFile = config.age.secrets."gandi.env".path;
997 };
998
999 environment.systemPackages = with pkgs; [
1000 lm_sensors
1001 gnumake
1002 ffmpeg-full
1003 ];
1004
1005}