nixfiles/profiles/usbAutoMount.nix
2023-09-19 22:30:02 +01:00

41 lines
1.3 KiB
Nix

{pkgs, ...}: let
encryptedUSB = import ../data/encryptedUSB.nix;
encUSBMount = pkgs.writeShellScriptBin "enc_usb_mount" ''
set -x
${encUSBUnmount}/bin/enc_usb_unmount
cat /secrets/usb_encryption_passphrase | cryptsetup luksOpen ${encryptedUSB.encryptedPath} ${encryptedUSB.mapperName} -
mount ${encryptedUSB.mapperPath} -o rw ${encryptedUSB.mountpoint}
'';
encUSBUnmount = pkgs.writeShellScriptBin "enc_usb_unmount" ''
set -x
umount -flR ${encryptedUSB.mountpoint} || true
cryptsetup close ${encryptedUSB.mapperName} || true
'';
in {
environment.systemPackages = [encUSBMount encUSBUnmount];
systemd.tmpfiles.rules = ["d ${encryptedUSB.mountpoint} - chaos root"];
systemd.services.enc-usb-mount = {
path = [pkgs.util-linux pkgs.cryptsetup];
wantedBy = ["multi-user.target"];
script = ''
${encUSBMount}/bin/enc_usb_mount
'';
};
systemd.services.enc-usb-unmount = {
path = [pkgs.util-linux pkgs.cryptsetup];
script = ''
${encUSBMount}/bin/enc_usb_unmount
'';
};
services.udev.extraRules = ''
ACTION=="add", ENV{PARTNAME}=="${encryptedUSB.encryptedPartLabel}", ENV{SYSTEMD_WANTS}="enc-usb-mount.service", ENV{UDISKS_PRESENTATION_HIDE}="1"
ACTION=="remove", ENV{PARTNAME}=="${encryptedUSB.encryptedPartLabel}", ENV{SYSTEMD_WANTS}="enc-usb-unmount.service"
'';
}