diff --git a/machines/fuuko/configuration.nix b/machines/fuuko/configuration.nix index b8a3c46..1df4ede 100644 --- a/machines/fuuko/configuration.nix +++ b/machines/fuuko/configuration.nix @@ -13,6 +13,7 @@ ./services/grafana.nix ./services/hedgedoc.nix ./services/matrix + ./services/media-backup.nix ./services/media.nix ./services/prometheus.nix ./services/scan.nix diff --git a/machines/fuuko/services/media-backup.nix b/machines/fuuko/services/media-backup.nix new file mode 100644 index 0000000..7db0d1d --- /dev/null +++ b/machines/fuuko/services/media-backup.nix @@ -0,0 +1,62 @@ +# This creates a backup of my media files when a specific hard drive is +# hotplugged. The hard drive has a btrfs filesystem inside of a luks container. +# The filesystem can be created with commands similar to this: +# cryptsetup luksFormat --label="fuuko-media-backup-luks" --key-file=/path/to/key /dev/sdb +# mkfs.btrfs -L "fuuko-media-backup" /dev/mapper/media-backup +{ lib, pkgs, ... }: +let + baseDir = "/data/media"; + mountPoint = "/mnt/media-backup"; +in +{ + # Systemd mount units do not support cryptsetup + systemd.services.media-backup-luks = { + after = [ ''dev-disk-by\x2dlabel-fuuko\x2dmedia\x2dbackup\x2dluks.device'' ]; + bindsTo = [ ''dev-disk-by\x2dlabel-fuuko\x2dmedia\x2dbackup\x2dluks.device'' ]; + unitConfig = { + StopWhenUnneeded = true; + }; + + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = "yes"; + ExecStart = "${pkgs.cryptsetup}/bin/cryptsetup open --type luks2 --key-file=${baseDir}/.backup-key /dev/disk/by-label/fuuko-media-backup-luks media-backup"; + ExecStop = "${pkgs.cryptsetup}/bin/cryptsetup close media-backup"; + }; + }; + + systemd.mounts = lib.singleton { + after = [ "media-backup-luks.service" ]; + bindsTo = [ "media-backup-luks.service" ]; + unitConfig = { + StopWhenUnneeded = true; + }; + + what = "/dev/mapper/media-backup"; + where = mountPoint; + }; + + systemd.services.media-backup = { + wantedBy = [ ''dev-disk-by\x2dlabel-fuuko\x2dmedia\x2dbackup\x2dluks.device'' ]; + unitConfig = { + RequiresMountsFor = "/mnt/media-backup"; + }; + + script = '' + ${pkgs.rsync}/bin/rsync \ + --archive \ + --delete \ + --links \ + --partial \ + --recursive\ + --verbose \ + ${lib.escapeShellArg baseDir} \ + ${lib.escapeShellArg mountPoint} + ''; + serviceConfig = { + IOSchedulingClass = "best-effort"; + IOSchedulingPriority = 7; + Nice = 10; + }; + }; +}