#!/bin/sh
# =============================================================================
# autopkgtest "syslog": self-test of the fake /dev/log module.
#
# Many containers have no syslog socket.  Daemons and tools such as sudo,
# sssd or cron then print warnings or block.  fx_syslog_start provides a
# socket at /dev/log and collects the messages in $FX_LOGDIR/syslog.log, which
# is shown or saved as an artifact if the test fails.
#
# Needs root (creates /dev/log) and socat.
#
# HOW TO ADAPT THIS FILE
#  * In your own test, call fx_syslog_start BEFORE starting the daemon that
#    logs.  If the testbed already has a /dev/log socket nothing is changed.
#  * Run from a checkout:  FX_LIBDIR=$PWD/lib sh debian/tests/syslog
# =============================================================================
set -eu

LIB="${FX_LIBDIR:-/usr/share/autopkgtest-helper}"
export FX_LIBDIR="$LIB"
. "$LIB/fixtures.sh"
fx_need_root
fx_init
fx_load syslog

# Remember whether the testbed brought its own /dev/log; the checks on the
# captured message only make sense when our fake one is in use.
had_socket=0
if [ -S /dev/log ]; then had_socket=1; fi

fx_syslog_start
[ -S /dev/log ] || fx_fail "/dev/log is not a socket"

# Send one datagram the way syslog(3) does.  <14> is facility user, level info.
python3 - <<'PY'
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
s.connect("/dev/log")
s.send(b"<14>fxtest: hello syslog")
PY

if [ "$had_socket" -eq 0 ]; then
    # The message must show up in the library's syslog log; poll because the
    # socat process needs a moment to write it out.
    fx_wait_cmd 5 grep -q "hello syslog" "$FX_LOGDIR/syslog.log" ||
        fx_fail "message not captured"
    # Starting the module a second time, while the socket exists, must be a
    # harmless no-op (the child shell has its own library state).
    cat >"$FX_ROOT/sub.sh" <<SUB
. "$LIB/fixtures.sh"
fx_init
fx_load syslog
fx_syslog_start
SUB
    # second start inside the same state: socket exists, nothing to do
    sh "$FX_ROOT/sub.sh"
fi

echo "syslog: all tests passed"
