# GNU Shepherd --- Test that a service's stop procedure is called when dependent throws an error.
#
# 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 <https://www.gnu.org/licenses/>.

shepherd --version
herd --version

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

herd="herd -s $socket"

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

cat > "$conf"<<EOF
(use-modules (srfi srfi-26))
(register-services
 (list (service
        '(my-root)
        #:start (const #t)
        #:stop  (lambda _
                  (call-with-output-file "$stamp"
                                         (cut display "foo" <>)))
        #:respawn? #f)
       (service
        '(buggy)
        #:requirement '(my-root)
        #:start (const #t)
        #:stop  (lambda _
                  (throw 'an-error)))))
EOF

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

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

shepherd_pid="`cat $pid`"

$herd start my-root
$herd start buggy

$herd stop my-root

# Ensure 'my-root' was stopped despite the error while stopping 'buggy'
test -f "$stamp"

# Check the log messages
grep "Ignoring error while stopping buggy: (an-error)" "$log"
grep "Stopping service my-root..." "$log"
grep "Service my-root is now stopped." "$log"

$herd stop root

# The shepherd process should be done now, or real soon.
while kill -0 "$shepherd_pid"; do sleep 0.3; done
