From 62c788eb864ab597d4ddb909f234d85c305c81a0 Mon Sep 17 00:00:00 2001
From: Daniel Barlow <dan@telent.net>
Date: Wed, 22 Nov 2023 00:05:55 +0000
Subject: [PATCH] add hook to run maintenance mode instead of rebooting

---
 modules/s6/default.nix               |  8 +++++++-
 modules/s6/scripts/rc.shutdown.final | 30 ++++++++++++++++------------
 2 files changed, 24 insertions(+), 14 deletions(-)

diff --git a/modules/s6/default.nix b/modules/s6/default.nix
index 447c6bedf..dbb61c03a 100644
--- a/modules/s6/default.nix
+++ b/modules/s6/default.nix
@@ -118,7 +118,13 @@ let
           mode = "0755";
         };
         finish = {
-          file = quit "s6-svscan exited. Rebooting.";
+          file = ''
+            ${openConsole}
+            ifelse { test -x /run/maintenance/exec } { /run/maintenance/exec }
+            foreground { echo "s6-svscan exited. Rebooting." }
+            wait { }
+            ${s6-linux-init}/bin/s6-linux-init-hpr -fr
+          '';
           mode = "0755";
         };
         SIGINT = {
diff --git a/modules/s6/scripts/rc.shutdown.final b/modules/s6/scripts/rc.shutdown.final
index 3f46b8760..5344b7a5d 100755
--- a/modules/s6/scripts/rc.shutdown.final
+++ b/modules/s6/scripts/rc.shutdown.final
@@ -1,18 +1,22 @@
 #!/bin/sh -e
 
-### Things to do *right before* the machine gets rebooted or
-### powered off, at the very end of the shutdown sequence,
-### when all the filesystems are unmounted.
+##  s6-linux-init-shutdownd never tells s6-svscan to exit, so if
+##  you're running s6-linux-init, it's normal that your
+##  .s6-svscan/finish script is not executed.
 
-### This is a last resort hook; normally nothing should be
-### done here (your rc.shutdown script should have taken care
-### of everything) and you should leave this script empty.
+##  The place where you want to hack things is /etc/rc.shutdown.final,
+##  which is run by the stage 4 script right before the hard reboot.
+##  So you can do dirty stuff [...] which should clean up the
+##  s6-supervise and the foreground, and give control to
+##  .s6-svscan/finish.
 
-### Some distributions, however, may need to perform some
-### actions after unmounting the filesystems: typically if
-### an additional teardown action is required on a filesystem
-### after unmounting it, or if the system needs to be
-### pivot_rooted before it can be shut down, etc.
+## -- Laurent Bercot on skaware mailing list,
+##    https://skarnet.org/lists/skaware/1913.html
 
-### Those are all exceptional cases. If you don't know for
-### certain that you need to do something here, you don't.
+exec >/dev/console 2>&1
+
+# down, exit supervisor, wait, stay down
+s6-svc -dxwD /run/service/s6-linux-init-shutdownd
+# HUP, exit supervisor, wait, down
+s6-svc -hxwd /run/service/s6-svscan-log
+s6-svscanctl -b /run/service # abort