#!/bin/sh
#
# SPDX-FileCopyrightText: Peter Pentchev
# SPDX-License-Identifier: BSD-2-Clause
#
# A trivial test case for stdsyslog, the utility for logging programs' output
# to the system log

if [ -f 'tap-functions.sh' ]; then
	. tap-functions.sh
elif [ -f 't/tap-functions.sh' ]; then
	. t/tap-functions.sh
else
	echo 'Bail out! Could not find tap-functions.sh'
	exit 99
fi

if [ -z "$TEST_STDSYSLOG" ]; then
	skip_all_ 'The TEST_STDSYSLOG environment variable must be set'
fi

: ${STDSYSLOG:=./stdsyslog}

plan_ 12

f=`mktemp stdsyslog.test.XXXXXX`
pidf=`mktemp stdsyslog.test.pid.XXXXXX`
trap "rm -f '$f' '$pidf'" EXIT QUIT HUP INT TERM ALRM PIPE

${STDSYSLOG} -V > "$f"
if egrep -qe '^stdsyslog[[:space:]]+[[:digit:]]+(\.[[:digit:]]+)+[[:space:]]*$' "$f" && \
   ! egrep -qve '^stdsyslog[[:space:]]+[[:digit:]]+(\.[[:digit:]]+)+[[:space:]]*$' "$f"; then
	ok_ 'Version output'
else
	not_ok_ 'Version output'
	cat "$f" 1>&2
fi

test_stdsyslog() {
	if [ "$#" -lt 3 ]; then
		bailout_ 'Internal error: test_stdsyslog code desc [opts] cmd...'
	fi

	local exp desc res
	exp="$1"
	desc="$2"
	shift 2

	${STDSYSLOG} "$@" > "$f"
	res="$?"
	if [ "$res" = "$exp" ]; then
		ok_ "$desc"
	else
		not_ok_ "$desc - exit code $res, expected $exp"
		cat "$f" 1>&2
	fi
}

test_stdsyslog 0 'Normal stdout' echo 'stdsyslog test 1 case 2'
test_stdsyslog 0 'Normal stderr' sh -c 'echo stdsyslog test 1 case 3 1>&2'
test_stdsyslog 7 'Non-zero exit' sh -c 'echo stdsyslog test 1 case 4; exit 7'
test_stdsyslog 130 'SIGINT' sh -c 'echo stdsyslog test 1 case 5; kill -INT "$$"'

test_stdsyslog 0 'List of levels' -l
if egrep -qe '^info$' "$f" && egrep -qe '^notice$' "$f" &&
    egrep -qe '^err$' "$f"; then
	ok_ 'Common levels present'
else
	not_ok_ 'Common levels present'
	cat "$f" 1>&2
fi

test_stdsyslog 0 'List of facilities' -f list
if egrep -qe '^user$' "$f" && egrep -qe '^local3$' "$f"; then
	ok_ 'Common facilities present'
else
	not_ok_ 'Common facilities present'
	cat "$f" 1>&2
fi

test_stdsyslog 0 'Log stdout' -d '0:err' -d '1:info' echo 'stdsyslog test 1 case 8'
test_stdsyslog 0 'Log stdout and stderr' -d '1:err' -d '2:info' sh -c 'echo stdsyslog test 1 case 9 1>&2'
test_stdsyslog 0 'Specify a PID file' -p "$pidf" sh -c 'pid="$(cat '"'$pidf'"')"; if [ ! "$pid" = "$$" ]; then echo "read $pid instead of $$"; exit 1; fi'
