# GNU Shepherd --- Test system logging service for shepherd itself.
# 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-$$"
pid="t-pid-$$"
syslog_file="$PWD/t-syslog-$$"
syslog_socket="$PWD/t-syslog-socket-$$"

herd="herd -s $socket"

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

cat > "$conf" <<EOF
(use-modules (shepherd service system-log)
             (shepherd endpoints))

(define %endpoints
  (list (endpoint (make-socket-address AF_UNIX "$syslog_socket")
                  #:style SOCK_DGRAM)))

(register-services
  (list (system-log-service %endpoints
                            #:message-destination (const '("$syslog_file"))
                            #:kernel-log-file #f)
        (service
          '(logger)
          #:requirement '(syslogd)
          #:start (make-forkexec-constructor
                   '("$SHELL" "-c" "while true; do echo logging from \$\$; sleep 0.2; done"))
          #:stop (make-kill-destructor)
          #:respawn? #f)))
EOF


rm -f "$pid"

# Log to syslog, with syslog implemented by shepherd itself.
shepherd -I -s "$socket" -c "$conf" --syslog="$syslog_socket" --pid="$pid" &

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

$herd start system-log
$herd status system-log | grep running
grep "system-log started" "$syslog_file"

$herd start logger
grep "logger started" "$syslog_file"

logger_pid="$($herd status logger | grep "PID: [0-9]\+" \
  | sed -e's/^.* \([0-9]\+\)$/\1/g')"
kill -0 "$logger_pid"

until grep "logging from $logger_pid" "$syslog_file"; do sleep 0.2; done

# Check that what shepherd logs internally is saved as UTF-8.
cat >> "$conf" <<EOF
;; -*- coding: utf-8 -*-
(display "Party time! 🥳\n")
EOF
$herd load root "$conf"
until grep "Party time" "$syslog_file"; do sleep 0.3; done
grep "🥳" "$syslog_file"

$herd stop root
grep "Exiting" "$syslog_file"
