#!/bin/sh
#
# msmtp-scripts test framework
#
#    Copyright (C) 2019 Daniel F. Dickinson <cshored@thecshore.com>
#
#    This program 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.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#

OTS=SUCCESS

CURDIR="$(pwd)"
export CURDIR

for tscript in ./tests/scripts/t[0-9][0-9]*.sh; do
	export MSMTP_SKIP_CONF=true
	export MSMTP_OVERRIDE_CONF=./tmp/msmtpq-ng.rc
	export KCOV_BASE="kcov --exclude-path=${CURDIR}/tests,${CURDIR}/tmp,/usr/lib,/etc --exclude-pattern=msmtpq-ng.rc,.msmtpq-ng.rc,msmtpq-ng-mta.rc,fakeroot-sysv,fake-flock,lock-fail --bash-handle-sh-invocation ${CURDIR}/kcov-lock-queue"
	export KCOV_OUTSIDE="kcov --exclude-path=${CURDIR}/tests,${CURDIR}/tmp,/usr/lib,/etc --exclude-pattern=msmtpq-ng.rc,.msmtpq-ng.rc,msmtpq-ng-mta.rc,fakeroot-sysv,fake-flock,lock-fail ${CURDIR}/kcov-user-"
	export KCOV_THROUGH="kcov --exclude-path=${CURDIR}/tests,${CURDIR}/tmp,/usr/lib,/etc --exclude-pattern=msmtpq-ng.rc,.msmtpq-ng.rc,msmtpq-ng-mta.rc,fakeroot-sysv,fake-flock,lock-fail --bash-handle-sh-invocation ${CURDIR}/kcov-user-"

	TSRC=0

	if [ -n "$1" ]; then
		if [ "$1" = "$(basename "$tscript" .sh )" ]; then
			$tscript
			TSRC=$?
			OTS=SINGLE
			break
		fi
	else
		$tscript
		TSRC=$?
	fi

	if [ "$TSRC" != "0" ]; then
		OTS=FAIL
		break
	fi
done

if [ "$OTS" = "FAIL" ]; then
	echo "FAIL: Build completed"
	exit 3
elif [ "$OTS" = "SINGLE" ]; then
	exit 0
elif ./tests/scripts/cleanup_build_environment; then
	echo "PASS: Cleanup buld environment"
	echo "PASS: Build succeeded"
	exit 0
else
	echo "FAIL: Cleanup buld environment"
	echo "FAIL: Build completed"
	exit 3
fi

exit 3
