{ self, pkgs, lib, ... }: let externalDriveData = import "${self}/data/drives/raspberryExternalDrive.nix"; unlockExternalDrive = let jq = "${pkgs.jq}/bin/jq"; vault = "${pkgs.vault-bin}/bin/vault"; cryptsetup = "${pkgs.cryptsetup}/bin/cryptsetup"; in pkgs.writeShellScriptBin "unlock_external_drive" '' ${lockExternalDrive}/bin/lock_external_drive vault-login || true export VAULT_ADDR="https://vault.owo.monster" cat /root/.vault-token | ${vault} login - ${vault} kv get -format json "/private-public-keys/cryptsetup/raspberry-ext-drive" \ | ${jq} -r ".data.data.key" \ | base64 -d \ | ${cryptsetup} open ${externalDriveData.encryptedPath} ${externalDriveData.mapperName} --key-file=/dev/stdin ''; lockExternalDrive = let cryptsetup = "${pkgs.cryptsetup}/bin/cryptsetup"; in pkgs.writeShellScriptBin "lock_external_drive" '' ${cryptsetup} close ${externalDriveData.mapperName} || true ''; mountName = ( builtins.replaceStrings ["/"] ["-"] ( lib.strings.removePrefix "/" externalDriveData.mountpoint ) ) + ".mount"; in { environment.systemPackages = [ unlockExternalDrive lockExternalDrive ]; systemd.tmpfiles.rules = ["d ${externalDriveData.mountpoint} - root root"]; systemd.services.ext-drive-unlock = { path = with pkgs; [ util-linux cryptsetup getent ]; partOf = [mountName]; wantedBy = ["multi-user.target"]; serviceConfig = { User = "root"; Group = "root"; }; script = '' ${unlockExternalDrive}/bin/unlock_external_drive ''; }; systemd.mounts = [ { what = "${externalDriveData.mapperPath}"; where = "${externalDriveData.mountpoint}"; after = ["ext-drive-unlock.service"]; description = "Raspberry's External Encrypted Drive"; type = "btrfs"; options = "rw,compress=zstd"; mountConfig = { LazyUnmount = true; ForceUnmount = true; }; } ]; }