{pkgs, ...}: let
  encryptedUSB = import ../data/drives/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"
  '';
}