{
  pkgs,
  self,
  ...
}: let
  encryptedUSB = import "${self}/data/drives/encryptedUSB.nix";

  encUSBMount = pkgs.writeShellScriptBin "enc_usb_mount" ''
    export MAPPER_NAME=''${MAPPER_NAME:-${encryptedUSB.mapperName}}
    set -x
    ${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}
  '';

  encUSBUnmount = pkgs.writeShellScriptBin "enc_usb_unmount" ''
    export MAPPER_NAME=''${MAPPER_NAME:-${encryptedUSB.mapperName}}
    set -x
    umount -flR ${encryptedUSB.mountpoint} || true
    cryptsetup close $MAPPER_NAME || 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"
  '';
}