# GNU Shepherd --- Check whether 'halt' works.
# Copyright © 2024 Ludovic Courtès <ludo@gnu.org>
#
# This file is part of the GNU Shepherd.
#
# The GNU Shepherd is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.
#
# The GNU Shepherd is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the GNU Shepherd.  If not, see <http://www.gnu.org/licenses/>.

shepherd --version
herd --version

socket="t-socket-$$"
conf="t-conf-$$"
log="t-log-$$"
pid="t-pid-$$"
witness="t-powered-off-$$"

herd="herd -s $socket"

trap "cat $log || true; rm -f $socket $conf $log $witness;
      test -f $pid && kill \`cat $pid\` || true; rm -f $pid" EXIT

cat > "$conf" <<EOF
(register-services
 (list (service
	 '(a)
	 #:start (const #t)
         #:stop (lambda _ (throw 'boooo!)))  ;fails to stop
       (service
	 '(b)
         #:requirement '(a)
	 #:start (make-forkexec-constructor
                  '("$SHELL" "-c"
                    "trap 'echo ignoring SIGTERM' SIGTERM; while true; do sleep 1; done"))
         #:stop (make-kill-destructor #:grace-period 0.5)
	 #:respawn? #t)))
EOF

rm -f "$pid" "$socket"
shepherd -I -s "$socket" -c "$conf" --pid="$pid" --log="$log" &

while ! test -f "$pid"; do sleep 0.5 ; done

$herd start b
$herd status

service_pid="`$herd status b | grep PID \
   | sed -es'/.*PID: \([0-9]\+\)$/\1/g'`"
kill -0 "$service_pid"

# Now make sure the 'power-off' action works even in the face of a 'stop'
# method throwing an exception.

$herd eval root "(set! (@ (shepherd system) power-off)
   (lambda ()
     (open-output-file \"$PWD/$witness\")
     (primitive-exit 0)))"

rm -f "$witness"
halt -s "$socket"

kill -0 "$service_pid" && false
test -f "$witness"
while kill -0 "$(cat "$pid")"; do sleep 1; done
