# GNU Shepherd --- Handling termination of a process before 'start' completes.
# Copyright © 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

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
(register-services
  (list (service
          '(stops-early)
          #:start (lambda ()
                    (let ((pid (fork+exec-command
                                '("$SHELL" "-c" "echo \$\$ done; exit 42"))))
                      (format #t "got PID ~a; sleeping~%" pid)

                      ;; Wait until PID is gone.
                      (let loop ()
                        (when (false-if-exception (begin (kill pid 0) #t))
                          (sleep 0.5)
                          (loop)))

                      ;; Return PID, which is already gone.
                      pid))
          #:stop (make-kill-destructor)
          #:respawn? #f)))
EOF

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

# Wait till it's ready.
until test -f "$pid"; do sleep 0.3; done

$herd status
$herd start stops-early

# The process associated with 'stops-early' terminated while the service was
# still in 'starting' state; yet the service should be marked as stopped and
# the exit status that is reported should be correct.
until $herd status stops-early | grep stopped; do sleep 0.2; done
$herd status stops-early | grep 'exited with code 42'
