nixfiles/profiles/nixos/usbAutoMount.nix

47 lines
1.5 KiB
Nix
Raw Normal View History

2024-07-24 14:13:59 +01:00
{
pkgs,
self,
...
}: let
encryptedUSB = import "${self}/data/drives/encryptedUSB.nix";
2023-09-18 03:56:58 +01:00
2023-09-19 17:53:44 +01:00
encUSBMount = pkgs.writeShellScriptBin "enc_usb_mount" ''
export MAPPER_NAME=''${MAPPER_NAME:-${encryptedUSB.mapperName}}
2022-12-14 10:08:14 +00:00
set -x
2023-09-19 22:30:02 +01:00
${encUSBUnmount}/bin/enc_usb_unmount
cat /secrets/usb_encryption_passphrase | cryptsetup luksOpen ${encryptedUSB.encryptedPath} $MAPPER_NAME -
mount /dev/mapper/$MAPPER_NAME -o rw ${encryptedUSB.mountpoint}
2022-11-10 11:25:33 +00:00
'';
2022-12-14 10:11:51 +00:00
2023-09-19 17:53:44 +01:00
encUSBUnmount = pkgs.writeShellScriptBin "enc_usb_unmount" ''
2024-07-18 18:30:10 +01:00
export MAPPER_NAME=''${MAPPER_NAME:-${encryptedUSB.mapperName}}
set -x
umount -flR ${encryptedUSB.mountpoint} || true
cryptsetup close $MAPPER_NAME || true
2022-11-10 11:25:33 +00:00
'';
in {
2023-09-19 17:53:44 +01:00
environment.systemPackages = [encUSBMount encUSBUnmount];
2022-11-10 11:25:33 +00:00
2023-09-18 03:56:58 +01:00
systemd.tmpfiles.rules = ["d ${encryptedUSB.mountpoint} - chaos root"];
2022-11-10 11:25:33 +00:00
2022-12-14 10:08:14 +00:00
systemd.services.enc-usb-mount = {
path = [pkgs.util-linux pkgs.cryptsetup];
2022-12-14 10:08:14 +00:00
wantedBy = ["multi-user.target"];
2022-11-10 11:25:33 +00:00
script = ''
2023-09-19 17:53:44 +01:00
${encUSBMount}/bin/enc_usb_mount
2022-11-10 11:25:33 +00:00
'';
};
2022-12-14 10:08:14 +00:00
systemd.services.enc-usb-unmount = {
path = [pkgs.util-linux pkgs.cryptsetup];
2022-11-10 11:25:33 +00:00
script = ''
2023-09-19 22:30:02 +01:00
${encUSBMount}/bin/enc_usb_unmount
2022-11-10 11:25:33 +00:00
'';
};
services.udev.extraRules = ''
2023-09-18 03:56:58 +01:00
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"
2022-11-10 11:25:33 +00:00
'';
}