From 2b5f370781b28f537f053f9d74645e3092f18d0b Mon Sep 17 00:00:00 2001
From: Luc <luc@bijl.us>
Date: Sun, 17 Nov 2024 19:13:04 +0100
Subject: [PATCH] Add initramfs compliant zlevis-fetch.

---
 src/zlevis-fetch | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
 create mode 100644 src/zlevis-fetch

diff --git a/src/zlevis-fetch b/src/zlevis-fetch
new file mode 100644
index 0000000..8658524
--- /dev/null
+++ b/src/zlevis-fetch
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+# Exit immediately if a command exits with a non-zero status
+set -e
+
+# Check if zlevis-decrypt is present
+command -v zlevis-decrypt > /dev/null || exit 1
+
+# Read ZFS dataset information.
+zfs list -Ho name,encryption,keystatus,encryptionroot,tpm:jwe | while IFS=$'\t' read -r ds enc keystatus encroot jwe; do
+	# Check if the dataset is the encryption root.
+    if [ "$ds" = "$encroot" ] && [ "$enc" != "off" ] && [ "$key" != "-" ]; then
+        if [ "$keystatus" = "available" ]; then
+            echo "Pool $ds already unlocked"
+        else
+            echo "Loading key for $ds"
+            if echo -n "$jwe" | zlevis-decrypt | zfs load-key -L prompt "$ds"; then
+                echo "Unlocked $ds"
+            else
+                echo "FAILED TO UNLOCK $ds" >&2
+				exit 1
+            fi
+        fi
+    fi
+done
\ No newline at end of file