# GNU Shepherd --- Check the 'daemonize' action of the root service.
# Copyright © 2023-2025 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

case "$("$GUILE" -c '(display (version))'):${SHEPHERD_DISABLE_SIGNALFD:-0}:$(uname)" in
    *:0:Linux)
	# Assuming 'signalfd' support: all is good.
	;;
    3.0.[0-9]:* | 2.*)
	echo "This test is known to fail with Guile <= 3.0.9 \
and without 'signalfd' support." >&2
	echo "See <https://issues.guix.gnu.org/68087>." >&2
	exit 77;;
esac

socket="t-socket-$$"
conf="t-conf-$$"
log="t-log-$$"
pid="t-pid-$$"

herd="herd -s $socket"

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

cat > "$conf" <<EOF
(define s
  (service
    '(a)
    #:start (make-system-constructor "echo STARTING")
    #:stop (make-system-destructor "echo STOPPING")))

(register-services (list s))

(perform-service-action root-service 'daemonize)

(start-service s)
EOF

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

until test -f "$pid"; do sleep 0.5; done

# Wait until it has daemonized.
until grep "Now running as process [0-9]" "$log"; do sleep 0.2; done

# This command should display shepherd's own PID, post-daemonize.
new_pid="$($herd eval root '(getpid)' | tail -1)"
kill -0 "$new_pid"
$herd status root | grep "PID: $new_pid"

$herd status
until $herd status a | grep running; do sleep 0.3; done

# Were the non-blocking bindings for 'sleep', 'system*', etc. preserved after
# daemonization?  Check the 'sleep' binding.
$herd eval root '(when (eq? sleep (@ (fibers) sleep)) (display "GOOD\n"))' \
      | grep GOOD

# If it's the non-blocking 'sleep' variant, the 'herd status' command below
# completes immediately; otherwise it blocks until 'sleep' terminates.
$herd eval root '(sleep 500)' &
$herd status

$herd stop root
