From 74f2aa62474c670fbbd1d1e824c692cd43056f33 Mon Sep 17 00:00:00 2001
From: Daniel Barlow <dan@telent.net>
Date: Sat, 6 May 2023 23:03:51 +0100
Subject: [PATCH] initramfs-peek: an initramfs image with a shell, for
 debugging

---
 pkgs/default.nix                |  1 +
 pkgs/initramfs-peek/default.nix | 37 +++++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+)
 create mode 100644 pkgs/initramfs-peek/default.nix

diff --git a/pkgs/default.nix b/pkgs/default.nix
index ad3855e71..7e4feb45f 100644
--- a/pkgs/default.nix
+++ b/pkgs/default.nix
@@ -45,6 +45,7 @@
 
   openwrt = callPackage ./openwrt {};
 
+  initramfs-peek = callPackage ./initramfs-peek {};
   min-copy-closure = callPackage ./min-copy-closure {};
   hi = callPackage ./hi {};
 }
diff --git a/pkgs/initramfs-peek/default.nix b/pkgs/initramfs-peek/default.nix
new file mode 100644
index 000000000..39067cb9b
--- /dev/null
+++ b/pkgs/initramfs-peek/default.nix
@@ -0,0 +1,37 @@
+{
+  busybox
+, pkgsBuildBuild
+, runCommand
+, cpio
+, writeReferencesToFile
+, writeScript
+} :
+let
+  inherit (pkgsBuildBuild) gen_init_cpio;
+  script =  writeScript "init" ''
+    #!/bin/sh
+    exec >/dev/console
+    echo Running in initramfs
+    PATH=${busybox}/bin:$PATH
+    export PATH
+    mount -t proc none /proc
+    mount -t sysfs none /sys
+    ${busybox}/bin/sh
+  '';
+  refs = writeReferencesToFile busybox;
+in runCommand "initramfs.cpio" { } ''
+  cat << SPECIALS | ${gen_init_cpio}/bin/gen_init_cpio /dev/stdin > out
+  dir /proc 0755 0 0
+  dir /sys 0755 0 0
+  dir /dev 0755 0 0
+  nod /dev/console 0600 0 0 c 5 1
+  nod /dev/mtdblock0 0600 0 0 b 31 0
+  dir /nix 0755 0 0
+  dir /nix/store 0755 0 0
+  dir /bin 0755 0 0
+  file /bin/sh  ${busybox}/bin/sh 0755 0 0
+  file /init ${script} 0755 0 0
+  SPECIALS
+  find $(cat ${refs}) | ${pkgsBuildBuild.cpio}/bin/cpio -H newc -o -A -v -O out
+  cp out $out
+''