#!/bin/sh
#
# Copyright (c) 2015  Peter Pentchev
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# A test for stdsyslog's signal forwarding and processing

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_ 6

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

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 130 'SIGINT to the parent' sh -c 'ppid=`ps -ho ppid "$$"`; kill -INT "$ppid"; sleep 1'
test_stdsyslog 0 'SIGINT caught' -d 0:info sh -c 'trap "echo ignoring a SIGINT" INT; ppid=`ps -ho ppid "$$"`; kill -INT "$ppid"; sleep 1'
if fgrep -qe 'ignoring a SIGINT' "$f"; then
	ok_ 'SIGINT caught indeed'
else
	not_ok_ 'SIGINT caught indeed'
	cat "$f" 1>&2
fi

test_stdsyslog 143 'SIGTERM to the parent' sh -c 'ppid=`ps -ho ppid "$$"`; kill -TERM "$ppid"; sleep 1'
test_stdsyslog 0 'SIGTERM caught' -d 0:info sh -c 'trap "echo ignoring a SIGTERM" TERM; ppid=`ps -ho ppid "$$"`; kill -TERM "$ppid"; sleep 1'
if fgrep -qe 'ignoring a SIGTERM' "$f"; then
	ok_ 'SIGTERM caught indeed'
else
	not_ok_ 'SIGTERM caught indeed'
	cat "$f" 1>&2
fi
